[Spring MVC] Spring Jdbc 정리 (SimpleJdbcInsert)
오늘은 좀 특이한 SimpleJdbcInsert라는 클래스를 알아보자.
SimpleJdbcInsert클래스는 쿼리문을 사용하지 않고 데이터를 삽입할 수 있게 해준다.
(대신 직접 테이블 명을 설정해야한다.)
먼저 JdbcTemplate과 NamedParameterJdbcTemplate과 같이 DB접속을 위해 DataSource를 파라미터로 넣어줬다.
그리고 생성된 SimpleJdbcInsert객체에 withTableName() 또는 setTableName()메서드를 사용해서
사용할 테이블명을 넣어준다.
또 usingColumns()메서드를 통해 입력할 필드명도 지정해 줄 수 있다.
아래 코드와 같이 메서드 체이닝을 통해 여러 메서드들을 이어줄수도있다.
...
@Repository
public class StudentDao {
private SimpleJdbcInsert jdbcTemplate;
public StudentDao(DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcInsert(dataSource);
jdbcTemplate.withTableName("student").usingColumns("name","age");
}
}
데이터를 삽입하기 위해서 SimpleJdbcInsert는 크게 execute()와 executeAndReturnKey()메서드를 지원한다.
파라미터로는 Map과 SqlParameterSource(BeanPropertySqlParameterSource, MapSqlParameterSource) 이렇게 두 가지 방법이 있다.
두 가지 방법 모두 이전에 사용해본 경험이 있다. 그래서 간단하게 코드로만 작성하겠다.
execute()
(1) Map방식
public int insertStudent(Student student) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("name", student.getName());
param.put("age", student.getAge());
int result = jdbcTemplate.execute(param);
return result;
}
(2) SqlParameterSource방식 (BeanPropertySqlParameterSource, MapSqlParameterSource)
public int insertStudent(Student student) {
SqlParameterSource param = new BeanPropertySqlParameterSource(student);
int result = jdbcTemplate.execute(param);
return result;
}
public int insertStudent(Student student) {
MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("name", student.getName());
param.addValue("age", student.getAge());
int result = jdbcTemplate.execute(param);
return result;
}
executeAndReturnKey()
executeAndReturnKey를 사용하기 위해서 테이블에 PRIMARY KEY가 있어야하고 자동으로 증가되는 설정을 해줘야한다.
student 테이블에 그러한 칼럼이 없어서 ALTER문을 통해 새로 추가해줬다.
-> alter table student add id int NOT NULL AUTO_INCREMENT PRIMARY KEY;
그리고 자동으로 등록되는 키가 무엇인지 알 수 있도록 SimpleJdbcInsert객체에
.setGeneratedKeyName("칼럼명") 메서드를 추가한다.
@Repository
public class StudentDao {
private SimpleJdbcInsert jdbcTemplate;
public StudentDao(DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcInsert(dataSource);
jdbcTemplate.withTableName("student")
.usingColumns("name","age")
.setGeneratedKeyName("id");
}
}
이제 데이터를 넣어보자
(1) Map방식
## 주의!
executeAndReturnKey의 반환형은 Number이므로 형변환을 해줘야 한다.
public int insertStudent(Student student) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("name", student.getName());
param.put("age", student.getAge());
Number genkey = jdbcTemplate.executeAndReturnKey(param);
return genkey.intValue();
}
(2) SqlParameterSource방식 (BeanPropertySqlParameterSource, MapSqlParameterSource)
public int insertStudent(Student student) {
SqlParameterSource param = new BeanPropertySqlParameterSource(student);
Number genkey = jdbcTemplate.executeAndReturnKey(param);
return genkey.intValue();
}
public int insertStudent5(Student student) {
MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("name", student.getName());
param.addValue("age", student.getAge());
Number genkey = jdbcTemplate.executeAndReturnKey(param);
return genkey.intValue();
}
정리하면 아래 사진과 같다.