Skip to content

Commit

Permalink
[JDBC 라이브러리 구현하기 - 1단계] 바론(이소민) 미션 제출합니다. (#305)
Browse files Browse the repository at this point in the history
* 패키지 위치 변경 및 코드 정리

* feat: JdbcTemplate update, query 메서드 구현

* feat: UserDao 추가 기능 구현

* refactor: UserDao DataSource 제거

* feat: UserDao 투두 로직 구현

---------

Co-authored-by: kang-hyungu <[email protected]>
  • Loading branch information
somsom13 and kang-hyungu authored Oct 1, 2023
1 parent 7182a49 commit 37ae787
Show file tree
Hide file tree
Showing 7 changed files with 107 additions and 95 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
# JDBC 라이브러리 구현하기

### 1단계
- [x] JdbcTemplate insert, update, delete, select 쿼리 메서드 구현
- [x] UserDao rowmapper 구현
- [x] UserDao todo 쿼리 로직 구현
116 changes: 24 additions & 92 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
@@ -1,121 +1,53 @@
package com.techcourse.dao;

import com.techcourse.domain.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class UserDao {

private static final Logger log = LoggerFactory.getLogger(UserDao.class);

private final DataSource dataSource;
private static final RowMapper<User> ROW_MAPPER = (rs, count) ->
new User(
rs.getLong("id"),
rs.getString("account"),
rs.getString("password"),
rs.getString("email")
);

public UserDao(final DataSource dataSource) {
this.dataSource = dataSource;
}
private final JdbcTemplate jdbcTemplate;

public UserDao(final JdbcTemplate jdbcTemplate) {
this.dataSource = null;
this.jdbcTemplate = jdbcTemplate;
}

public void insert(final User user) {
final var sql = "insert into users (account, password, email) values (?, ?, ?)";

Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);

log.debug("query : {}", sql);

pstmt.setString(1, user.getAccount());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getEmail());
pstmt.executeUpdate();
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException ignored) {}
final String sql = "insert into users (account, password, email) values (?, ?, ?)";

try {
if (conn != null) {
conn.close();
}
} catch (SQLException ignored) {}
}
jdbcTemplate.update(sql, user.getAccount(), user.getPassword(), user.getEmail());
}

public void update(final User user) {
// todo
final String sql = "update users set account = ?, password = ?, email = ? where id = ?";

jdbcTemplate.update(sql, user.getAccount(), user.getPassword(), user.getEmail(), user.getId());
}

public List<User> findAll() {
// todo
return null;
final String sql = "select id, account, email, password from users";

return jdbcTemplate.query(sql, ROW_MAPPER);
}

public User findById(final Long id) {
final var sql = "select id, account, password, email from users where id = ?";

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, id);
rs = pstmt.executeQuery();

log.debug("query : {}", sql);
final String sql = "select id, account, password, email from users where id = ?";

if (rs.next()) {
return new User(
rs.getLong(1),
rs.getString(2),
rs.getString(3),
rs.getString(4));
}
return null;
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException ignored) {}

try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException ignored) {}

try {
if (conn != null) {
conn.close();
}
} catch (SQLException ignored) {}
}
return jdbcTemplate.queryForObject(sql, ROW_MAPPER, id);
}

public User findByAccount(final String account) {
// todo
return null;
final String sql = "select id, account, password, email from users where account = ?";

return jdbcTemplate.queryForObject(sql, ROW_MAPPER, account);
}
}
3 changes: 2 additions & 1 deletion app/src/test/java/com/techcourse/dao/UserDaoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import static org.assertj.core.api.Assertions.assertThat;

Expand All @@ -16,7 +17,7 @@ class UserDaoTest {
void setup() {
DatabasePopulatorUtils.execute(DataSourceConfig.getInstance());

userDao = new UserDao(DataSourceConfig.getInstance());
userDao = new UserDao(new JdbcTemplate(DataSourceConfig.getInstance()));
final var user = new User("gugu", "password", "[email protected]");
userDao.insert(user);
}
Expand Down
66 changes: 64 additions & 2 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package org.springframework.jdbc.core;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;

public class JdbcTemplate {

private static final Logger log = LoggerFactory.getLogger(JdbcTemplate.class);
Expand All @@ -14,4 +19,61 @@ public class JdbcTemplate {
public JdbcTemplate(final DataSource dataSource) {
this.dataSource = dataSource;
}

public <T> List<T> query(final String sql, final RowMapper<T> rowMapper, final Object... args) {
try (final Connection connection = dataSource.getConnection();
final PreparedStatement pstmt = connection.prepareStatement(sql)) {
log.debug("query : {}", sql);

setParamsToPreparedStatement(pstmt, args);

final ResultSet resultSet = pstmt.executeQuery();
final List<T> results = new ArrayList<>();
if (resultSet.next()) {
results.add(rowMapper.mapRow(resultSet, resultSet.getRow()));
}

return results;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

private void setParamsToPreparedStatement(final PreparedStatement pstmt, final Object[] args)
throws SQLException
{
for (int i = 0; i < args.length; i++) {
pstmt.setObject(i + 1, args[i]);
}
}

public <T> T queryForObject(final String sql, final RowMapper<T> rowMapper, final Object... args) {
try (final Connection connection = dataSource.getConnection();
final PreparedStatement pstmt = connection.prepareStatement(sql)) {
log.debug("query : {}", sql);

setParamsToPreparedStatement(pstmt, args);

final ResultSet resultSet = pstmt.executeQuery();
if (resultSet.next()) {
return rowMapper.mapRow(resultSet, resultSet.getRow());
}
return null;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

public int update(final String sql, final Object... args) {
try (final Connection connection = dataSource.getConnection();
final PreparedStatement pstmt = connection.prepareStatement(sql)) {
log.debug("query : {}", sql);

setParamsToPreparedStatement(pstmt, args);

return pstmt.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
10 changes: 10 additions & 0 deletions jdbc/src/main/java/org/springframework/jdbc/core/RowMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.springframework.jdbc.core;

import java.sql.ResultSet;
import java.sql.SQLException;

@FunctionalInterface
public interface RowMapper<T> {

T mapRow(final ResultSet resultSet, final int count) throws SQLException;
}
1 change: 1 addition & 0 deletions study/src/main/java/aop/config/DataSourceConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public class DataSourceConfig {
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.setName("test;DB_CLOSE_DELAY=-1;MODE=MYSQL;")
.addScript("classpath:schema.sql")
.build();
}
Expand Down
1 change: 1 addition & 0 deletions study/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
spring:
jpa:
open-in-view: false
show-sql: true
generate-ddl: true
hibernate:
Expand Down

0 comments on commit 37ae787

Please sign in to comment.