JDBC 코딩할 때 골치아픈 것 중의 하나가 generate key(오라클의 sequence, MS SQL의 identity, MySQL의 auto_increment 등)을 다루는 것이다.
JDBC 3.0부터는 여기에 대한 API가 추가(자바 1.4 이후에)되어 편하게 쓸 수 있지만...
아 글쎄~ 요즘세상에 JDBC를 날로 쓰는 경우가 어딨냐고-.-;
ORM까지 동원하기엔 좀 그렇고-.-, 그렇다고 JDBC를 날로 쓰기도 좀 그렇고...
이럴 땐, commons-dbutils나 spring-jdbc를 사용하게 된다.
commons-dbutils를 사용하는 경우는 사실상 JDBC를 날로 쓸 때와 큰 차이가 없으니 넘어가고...
spring-jdbc을 사용하는 경우, 그 중에서도 스프링 2.5부터 추가된 SimpleJdbcInsert의 경우를 알아보면:
SimpleJdbcInsert insert = new SimpleJdbcInsert(dataSource).withTableName("contacts").usingGeneratedKeyColumns("id");
SqlParameterSource paramSource = new BeanPropertySqlParameterSource(contact);
long generatedKey = insert.executeAndReturnKey(paramSource).longValue();
contact.setId(generatedKey);
"와~~ 깔끔하게 끝나네~"라고 기뻐하려는 찰라... 이게 derby에서(만!) 안된다. ㅠ.ㅠ
좀 뒤져봤더니 버그만 올라와 있고 해결책은 안 나와 있다. 그래서... 이렇게 구질구질한 코드를 만들었다:
KeyHolder keyHolder = new GeneratedKeyHolder();
JdbcTemplate template = new JdbcTemplate(dataSource);
template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection)
throws SQLException {
PreparedStatement pstmt = connection.prepareStatement("INSERT INTO contacts(name,email,address) VALUES(?,?,?)", Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, contact.getName());
pstmt.setString(2, contact.getEmail());
pstmt.setString(3, contact.getAddress());
return pstmt;
}
}, keyHolder);
Long generatedKey = new Long(keyHolder.getKey().longValue());
book.setId(generatedKey);
혹시, 더 깔끔한 방법을 알고 있는 분 계시면 공유 좀 해주셈~~
'hacking > java' 카테고리의 다른 글
| Google AppEngine(Java) 삽질기... (0) | 2009/05/18 |
|---|---|
| spring-jdbc에서 derby의 generated key 받기 (0) | 2009/01/18 |
| Mac OSX에서 넷빈즈 이쁘게 쓰기 (2) | 2009/01/17 |
| 자바 환경에서 XQuery 사용하기 (4) | 2008/10/29 |
| SUN TECH DAYS 2008 Seoul (3) | 2008/09/24 |
| 웹 어플리케이션에 OSGi 컨테이너(FELIX) 내장하기 (1) (0) | 2008/08/02 |