-
[김영한 스프링] 16. 스프링 JdbcTemplateSpring/스프링 입문 2023. 3. 30. 22:05
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class JdbcTemplateMemberRepository implements MemberRepository {
private final JdbcTemplate jdbcTemplate;
public JdbcTemplateMemberRepository(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Member save(Member member) {
SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
jdbcInsert.withTableName("member").usingGeneratedKeyColumns("id");
Map<String, Object> parameters = new HashMap<>();
parameters.put("name", member.getName());
Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(parameters));
member.setId(key.longValue());
return member;
}
@Override
public Optional<Member> findById(Long id) {
List<Member> result = jdbcTemplate.query("select * from member where id = ?", memberRowMapper(), id);
return result.stream().findAny();
}
@Override
public List<Member> findAll() {
return jdbcTemplate.query("select * from member", memberRowMapper());
}
@Override
public Optional<Member> findByName(String name) {
List<Member> result = jdbcTemplate.query("select * from member where name = ?", memberRowMapper(), name);
return result.stream().findAny();
}
private RowMapper<Member> memberRowMapper() {
return (rs, rowNum) -> {
Member member = new Member(); member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
return member;
};
}
}hello.hellospring/repository/JdbcTemplateMemberRepository생성
SimpleJdbcInsert는 sql을 작성하지 않아도 됨
withTableName : 테이블명
usingGeneratedKeyColumns : pk컬럼명
map에 insert시 사용할 컬럼을 넣어줌
return new JdbcTemplateMemberRepository(dataSource);로 변경
테스트 성공
'Spring > 스프링 입문' 카테고리의 다른 글
[김영한 스프링] 18. 스프링 데이터 JPA (0) 2023.04.01 [김영한 스프링] 17. JPA (0) 2023.03.31 [김영한 스프링] 15. 스프링 통합 테스트 (0) 2023.03.30 [김영한 스프링] 14. JDBC (0) 2023.03.29 [김영한 스프링] 13. H2 데이터베이스 설치 (0) 2023.03.18