JDBC 템플릿 선언
public class Test{
private final JdbcTemplate template;
public Test(DataSource dataSource){
template = new JdbcTemplate(dataSource);
}
}
JDBC 템플릿 사용법
template.update([sql구문], [구문에필요한 파라미터1], [구문에필요한 파라미터2] ..)
template.update([sql구문], [RowMapper()] , [구문에필요한 파라미터2] ..)
private RowMapper<Member> testRowMapper() {
return (rs, rowNum) -> {
Object obj = new Object();
obj.setxxx(rs.getString("결과조회1"));
obj.setxxx(rs.getInt("결과조회2"));
return object;
}; }
예제
- Insert 구문은 결과값이 없어서 RowMapper() 필요없음
- select 구문은 결과값이 있어 RowMapper 필요
- .queryForObject()의 경우 Object를 반환함
public class Repository{
private final JdbcTemplate template;
public Repository(DataSource dataSource){
template = new JdbcTemplate(dataSource);
}
public Member save (Member member){
template.update("insert into member(member_id, money) values(?,?)", member.getMemberId(), member.getMoney());
return member;
}
public Member findById(String memberId){
return template.queryForObject("select* from member where member_id = ?" , memberRowMapper(), memberId);
}
private RowMapper<Member> memberRowMapper() {
return (rs, rowNum) -> {
Member member = new Member();
member.setMemberId(rs.getString("member_id"));
member.setMoney(rs.getInt("money"));
return member;
}; }
}