2012-05-24 1 views
0

최대 절전 모드 세션 'doWork() 메서드를 사용하면 java.sql.Connection에 직접 액세스 할 수 있습니다.시퀀스 ID 생성을 위해 최대 절전 모드 Session.doWork 사용

다음은이 작업을 수행 할 수있는 더 좋은 방법이있다, 만들고 PreparedStatement 순서를

public Long generateId() { 
    final Long id[] = { null }; 

    getSessionFactory().openSession().doWork(new Work() { 
     public void execute(Connection connection) throws SQLException { 
      PreparedStatement ps = connection 
        .prepareStatement("SELECT HIB_SEQ.nextval FROM DUAL"); 
      ResultSet rs = ps.executeQuery(); 
      while (rs.next()) { 
       id[0] = rs.getLong(0); 
      } 
     } 
    }); 
    return id[0]; 
} 

첫째을 생성하기 위해 실행할 수있는 방법 중 하나입니다?

두 번째 질문 위에서 작성한 PreparedStatement을 명시 적으로 닫아야합니까?

답변

0
String query = ((SessionFactoryImplementor)sessionFactory).getDialect().getSequenceNextValString(seqName); 
    Session session = sessionFactory.getCurrentSession(); 
    return (Long) session.createSQLQuery(query).addScalar("nextval", Hibernate.LONG).uniqueResult(); 

데이터베이스의 열 이름과 반환 유형에 맞게 스칼라 부분을 약간 조정할 수 있습니다.

0

PreparedStatement의 인스턴스 메소드 Work.execute의 일부로서 생성되고, 따라서 개폐 포함하는 범위 내에서 처리한다 (인스턴스 자체 GC에 의해 수집 될 것이다 방법은 범위 밖이 될 것이다 변수 ps 보낸 실행을 완료하지만, 일단 열린 커서와 같은 외부 리소스에는 명시 적 호출 ps.close()이 필요합니다.

반면에 Connection의 인스턴스는 Hibernate에 의해 메소드에 전달되며 수동으로 닫아서는 안된다. 이것은 Hibernate의 책임이다.

0

1) 값을 돌려주기 위해 우리가 사용할 수있는 doReturningWork

public int updateEmployeeStatusWithCount(final List<String> employeeList) throws DBException 
{ 
     Session session = null; 
     try 
     { 
       session = HibernateUtil.getSession(); 
       session.beginTransaction(); 
       int cnt = session.doReturningWork(new ReturningWork<Integer>() { 
        @Override 
        public Integer execute(Connection conn) throws SQLException { 
          PreparedStatement pStmt = null; 
          try 
          { 
            int updatedCnt = 0; 
            String sqlQry = "UPDATE EMP_DETAILS set IS_ACTIVE='N' WHERE EMP_ID=?"; 
            pStmt = conn.prepareStatement(sqlQry); 
            for(String empId:employeeList) 
            { 
             System.out.println(empId); 
             pStmt.setString(1, empId); 
             int cnt = pStmt.executeUpdate(); 
             updatedCnt+=cnt; 
            } 
            return updatedCnt; 
          } 
          finally 
          { 
            pStmt.close(); 
          }         
        } 
       }); 
       session.getTransaction().commit(); 
       return cnt; 
     } 
     catch(HibernateException e) 
     { 
       throw new DBException("Error occured while updating Employee Status",e); 
     } 
     finally 
     { 
       HibernateUtil.closeSession(session); 
     }    
} 

2) 예, 명시 적으로 예를

public void updateEmployeeStatus(final List<String> employeeList) throws DBException 
{ 
     Session session = null; 
     try 
     { 
       session = HibernateUtil.getSession(); 
       session.beginTransaction(); 
       session.doWork(new Work() { 
        @Override 
        public void execute(Connection conn) throws SQLException { 
          PreparedStatement pStmt = null; 
          try 
          { 
            String sqlQry = "UPDATE EMP_DETAILS set IS_ACTIVE='N' WHERE EMP_ID=?"; 
            pStmt = conn.prepareStatement(sqlQry); 
            for(String empId:employeeList) 
            { 
             pStmt.setString(1, empId); 
             pStmt.addBatch(); 
            } 
            pStmt.executeBatch(); 
          } 
          finally 
          { 
            pStmt.close(); 
          }         
        } 
       }); 
       session.getTransaction().commit(); 
     } 
     catch(HibernateException e) 
     { 
       throw new DBException("Error occured while updating Employee Status",e); 
     } 
     finally 
     { 
       HibernateUtil.closeSession(session); 
     }    
} 

Reference

아래 참조 PreparedStatement 을 닫아야