๋ฐ์ํ
์ค์ ์ ์์ Jdbc์ ๋์ผํ ํ๊ฒฝ์ค์ ์ ํ๋ฉด ๋๋ค.
์คํ๋ง JdbcTemplate๊ณผ Mybatis ๊ฐ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ JDBC API์์ ๋ณธ ๋ฐ๋ณต ์ฝ๋๋ฅผ ๋๋ถ๋ถ ์ ๊ฑฐํด์ค๋ค.
ํ์ง๋ง SQL์ ์ง์ ์์ฑ ํด์ผ ํ๋ค.
์คํ๋ง JdbcTemplate ํ์ ๋ฆฌํฌ์งํ ๋ฆฌ
package iseunghan.iseunghanspring.repository;
import iseunghan.iseunghanspring.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.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class JdbcTemplateMemberRepository implements MemberRepository {
//jdbcTemplate์ injection์ด ์๋๊ณ , datasource๋ฅผ ๋ฐ์์ ์์ฑ์๋ฅผ ํตํด ๋๊ฒจ์ค์ผ ํ๋ค.
private final JdbcTemplate jdbcTemplate;
// @Autowired : ์์ฑ์๊ฐ ๋จ 1๊ฐ์ด๊ณ , ์ด ํด๋์ค๊ฐ ๋น์ผ๋, Auotwired๋ฅผ ์๋ต ํ ์ ์๋ค.
public JdbcTemplateMemberRepository(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Member save(Member member) { //์ด๋ฐ๊ฒ ์๋ค ์ ๋๋ง.. ์์ธํ๊ฑด jdbc template ๋ฉ๋ด์ผ ์ฐธ
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 Optional<Member> findByName(String name) {
List<Member> result = jdbcTemplate.query("select * from member where name=?", memberRowMapper(),name);
return result.stream().findAny();
}
@Override
public List<Member> findAll() {
return jdbcTemplate.query("select * from member", memberRowMapper());
}
private RowMapper<Member> memberRowMapper(){
return (rs, rowNum) -> {
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
return member;
};
}
}
๋ฐ์ํ