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)是的,我们必须明确关闭PreparedStatement
见下面的例子
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);
}
}
参考