我们最近搬到了hibernate 4。我们的应用程序有许多文件,其中包含已弃用的 session.connection ()。我通过这样的调用替换了 session.doWork() :
session.doWork(new Work() {
@Override
public void execute(Connection conn) throws SQLException {
wasAuto = conn.getAutoCommit();
if(!wasAuto) {
conn.rollback(); // in case there is existing transaction
conn.setAutoCommit(true);
}
}
});
try {
return mainCallback.doInHibernate(session);
} finally {
session.doWork(new Work() {
@Override
public void execute(Connection conn) throws SQLException {
if(!wasAuto)
conn.setAutoCommit(wasAuto);
}
});
}
但正如我所说,我们有许多文件有相同的错误。像上面这样写是最佳实践吗?
为了更好地理解,我添加了一个有错误的文件。有人可以帮我清除错误。
Session session = repo.getSessionFactory().openSession();
Connection connection = null;
PreparedStatement ps = null;
int recordCount = 0;
try {
connection = session.connection();
ps = connection.prepareStatement(masterSql);
ps.setDate(1,acctPeriod);
ps.setLong(2,geoScheme.getId());
recordCount = ps.executeUpdate();
long millis = System.currentTimeMillis() - start;
logger.info("END --> Generating/Running Dynamic SQL for Aggregation took "+(millis / 60000.0)+" min" );
run.addRollupMessage("Generating/Running Dynamic SQL for Aggregation took "+(millis / 60000.0)+" min" );
run.setEndDate(DateUtils.currentTimestamp());
logger.info("No of Loan groups inserted = " + recordCount);
run.addRollupMessage("No of Loan groups inserted = " + recordCount);
} catch (Exception err) {
throw new RuntimeException(" **ERROR** DURING AGGREGATION: " + err.getMessage(),err);
}
finally
{
if (ps != null) ps.close();
if (connection != null) connection.close();
if (session != null) session.close();
}