이상한 코딩 나라의 혜돌이
[JAVA] Sequence를 이용하여 생성한 PK값을 알아내는 방법 본문
보통 DB에서 레코드를 생성할 때, id값은 sequence를 이용하여 생성한다.
우리 팀도 그렇게 쿼리를 짜 뒀었다.
그런데... a를 insert하고, 곧이어 a의 id를 FK로 받는 b 레코드를 insert하는 경우 문제가 생겼다.
id값을 모르는 데 어떻게 b를 insert하지 ...? id를 모르니까 검색할 수도 없는데 ..
끙끙 앓고 있는데 교수님이 문제를 명쾌하게 해결해 주셨다.
우선 Connection 연결하는 곳에 다음 세 메소드를 추가한다.
// PK 컬럼 이름 배열을 이용하여 PreparedStatement를 생성
private PreparedStatement getPreparedStatement(String[] columnNames) throws SQLException {
if (conn == null) {
conn = connMan.getConnection();
conn.setAutoCommit(false);
}
if (pstmt != null) pstmt.close();
pstmt = conn.prepareStatement(sql, columnNames);
// JDBCUtil.printDataSourceStats(ds);
return pstmt;
}
// 위 메소드를 이용하여 PreparedStatement 를 생성한 후 executeUpdate 실행
public int executeUpdate(String[] columnNames) throws SQLException, Exception {
pstmt = getPreparedStatement(columnNames); // 위 메소드를 호출
int parameterSize = getParameterSize();
for (int i = 0; i < parameterSize; i++) {
if (getParameter(i) == null) { // 매개변수 값이 널이 부분이 있을 경우
pstmt.setString(i + 1, null);
} else {
pstmt.setObject(i + 1, getParameter(i));
}
}
return pstmt.executeUpdate();
}
// PK 컬럼의 값(들)을 포함하는 ResultSet 객체 구하기
public ResultSet getGeneratedKeys() {
try {
return pstmt.getGeneratedKeys();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
그리고 생성된 PK값을 알고 싶은 곳에서 다음과 같이 메소드를 사용하면 된다.
String insertQuery = "INSERT INTO T1 VALUES (myseq.nextval, ?, ?, ?, ?)"
Object[] param = new Object[] {...};
jdbcUtil.setSqlAndParameters(insertQuery, param); // JDBCUtil 에 insert문과 매개 변수 설정
String key[]={"user_id"};// PK 컬럼(들)의 이름 배열
try {
int result = jdbcUtil.executeUpdate(key); // insert 문 실행
ResultSet rs = jdbcUtil.getGeneratedKeys();
int generatedKey = 0;
if(rs.next()){
generatedKey = rs.getInt(1); // 생성된 PK 값 (인덱스 지정)
// 위의 키 값을 이용하여 작업 실행 ...
}
return result;
}
구글링 해도 절대로 안 나오길래 .. 꼭 포스팅하고 싶었음.
교수님 감사해요 헤헤
'Study > Troubleshooting' 카테고리의 다른 글
[C] printf, write 함수에 대해서 (0) | 2018.12.03 |
---|---|
[C] 소켓 서버를 돌릴 때 발생하는 bind error (0) | 2018.12.03 |
[AWS] EC2 ssh 접속 시 Permission denied 현상 (3) | 2018.09.17 |
[Linux] make 명령어에서 clean의 dependency list에 대한 의문 (0) | 2018.09.13 |
[JSP] AJAX 한글 처리 이슈 (0) | 2018.01.04 |