Skip to content

Commit

Permalink
feat: query 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
donghae-kim committed Sep 26, 2023
1 parent 2c578d4 commit e2fc3e5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
16 changes: 9 additions & 7 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@

public class UserDao {

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

private final JdbcTemplate jdbcTemplate;

private RowMapper<User> userRowMapper() {
Expand All @@ -38,12 +36,15 @@ public void insert(final User user) {
}

public void update(final User user) {
// todo
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;
String sql = "select * from users";

return jdbcTemplate.query(sql, userRowMapper());
}

public User findById(final Long id) {
Expand All @@ -53,7 +54,8 @@ public User findById(final Long id) {
}

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

return jdbcTemplate.queryForObject(sql, userRowMapper(), account);
}
}
21 changes: 21 additions & 0 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JdbcTemplate {

Expand Down Expand Up @@ -53,4 +55,23 @@ public <T> T queryForObject(final String sql, final RowMapper<T> rowMapper, fina
throw new RuntimeException(e);
}
}

public <T> List<T> query(final String sql, final RowMapper<T> rowMapper) {
try (final Connection conn = dataSource.getConnection();
final PreparedStatement pstmt = conn.prepareStatement(sql)) {

final List<T> results = new ArrayList<>();

log.debug("query : {}", sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
results.add(rowMapper.execute(rs));
}

return results;
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
}

0 comments on commit e2fc3e5

Please sign in to comment.