Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

이상한 코딩 나라의 혜돌이

[JAVA] Sequence를 이용하여 생성한 PK값을 알아내는 방법 본문

Study/Troubleshooting

[JAVA] Sequence를 이용하여 생성한 PK값을 알아내는 방법

혜돌이 2018. 1. 4. 01:50

보통 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;

 

 

구글링 해도 절대로 안 나오길래 .. 꼭 포스팅하고 싶었음.

교수님 감사해요 헤헤

 

 

Comments