Skip to content

Commit

Permalink
refactor: 쓰기 쿼리 부분 jdbcTemplate으로 리팩터링
Browse files Browse the repository at this point in the history
  • Loading branch information
hong-sile committed Sep 26, 2023
1 parent 2602ce1 commit 68029ad
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 29 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@
- [ ] findByAccount
- [ ] findById
- [ ] findAll
- [ ] update
- [ ] insert
- [x] update
- [x] insert
36 changes: 9 additions & 27 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.techcourse.dao;

import com.techcourse.config.DataSourceConfig;
import com.techcourse.domain.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
Expand All @@ -17,47 +18,28 @@ public class UserDao {
private static final Logger log = LoggerFactory.getLogger(UserDao.class);

private final DataSource dataSource;
private final JdbcTemplate jdbcTemplate;

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

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

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

try (final Connection connection = dataSource.getConnection();
final PreparedStatement pstmt = connection.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) {
throw new RuntimeException(e);
}
jdbcTemplate.executeUpdate(sql,
user.getAccount(), user.getPassword(), user.getEmail());
}

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

try (final Connection connection = dataSource.getConnection();
final PreparedStatement pstmt = connection.prepareStatement(sql)) {
log.debug("query : {}", sql);

pstmt.setString(1, user.getAccount());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getEmail());
pstmt.setLong(4, user.getId());
pstmt.executeUpdate();
} catch (final SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
jdbcTemplate.executeUpdate(sql,
user.getAccount(), user.getPassword(), user.getEmail(), user.getId());
}

public List<User> findAll() {
Expand Down

0 comments on commit 68029ad

Please sign in to comment.