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()