Transaction transaction = null; //定义一个transaction
Session currentSession = null;
try {
currentSession = this.getSessionFactory().getCurrentSession();
transaction = currentSession.getTransaction(); // 让新定义的transaction等于当前事务
currentSession.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//业务逻辑start
for (Integer carId : carIds) {
preparedStatement.setInt(1,primaryKeyId);
preparedStatement.setInt(2,carId);
preparedStatement.addBatch();
}
//业务逻辑end
preparedStatement.executeBatch();
}
});
// transaction.commit(); 因为整合的是SSH 事务机制交给了SPring所以不需要我们去掌控提交或回滚
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
throw new SQLException();
}
//tips:之前写了commit()方法直接报错,说事务已经存在,找了半天才发现是因为事务已经进行了托管管理,吧commit方法注掉直接顺利成功。根据自己项目结合查看是否进行commit()