Spring JDBC에서 DB 접근하는 방법 - SimpleJdbcTemplate
- JdbcTemplate의 모든 기능과 NamedParameterJdbcTemplate의 기능을 합친 것으로 자바5의 auto boxing과 varargs(String…args, 가변길이 매개변수) 기능을 포함하고 있다.
[JdbcTemplate Style]
public class PersonDao {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public Person findPerson(Integer id, String lastname) {
String sql = "select id, firstname, lastname from PERSON where id = ? and lastname = ?";
RowMapper<person> mapper = new RowMapper<person>() {
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person();
person.setId(rs.getLong("id"));
person.setFirstName(rs.getString("firstname"));
person.setLastName(rs.getString("lastname"));
return person;
}
};
// SELECT인 경우 Mapper가 뒤에 오고 그 앞에 매개변수들을 객체배열에 담아 넘긴다.
// Person 타입으로 형 변환도 필요하다.
return (Person) jdbcTemplate.queryForObject(sql, new Object[] {id, lastname}, mapper);
}
[SimpleJdbcTemplate Style]
public class PersonDao {
private SimpleJdbcTemplate simpleJdbcTemplate;
public void setDataSource(DataSource dataSource) {
this. simpleJdbcTemplate = new SimpleJdbcTemplate (dataSource);
}
public Person findPerson(Integer id, String lastname) {
String sql = "select id, firstname, lastname from PERSON where id = ? and lastname = ?";
RowMapper<person> mapper = new RowMapper<person>() {
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person();
person.setId(rs.getLong("id"));
person.setFirstName(rs.getString("firstname"));
person.setLastName(rs.getString("lastname"));
return person;
}
};
// SELECT인 경우 Mapper가 쿼리문 다음에 오고 그 뒤에 가변길이 매개변수 형태로 넘기는
// 객체배열 형태로 받는다. Person 타입으로 형 변환도 필요없다.
return simpleJdbcTemplate.queryForObject(sql, mapper, id, lastname);
}
#SimpleJdbcTemplate, #JPA, #JPA교육, #스프링부트, #스프링CRUD예제, #마리아DB, #스프링교육, #스프링동영상, #자바교육, #자바학원, #스프링학원, #스프링JDBC,
SimpleJdbcTemplate, JPA, JPA교육, 스프링부트, 스프링CRUD예제, 마리아DB, 스프링교육, 스프링동영상, 자바교육, 자바학원, 스프링학원, 스프링JDBC
댓글 없음:
댓글 쓰기