Understanding the source of a transaction
I often ask this question in the interview, if there is a global variable, in a transaction to modify the value of the variable, and then the transaction for other reasons rollback, then the value of this variable will be rolled back to the value before the change?
In fact, a transaction can only commit and rollback the resources it manages, and these resources are transaction sources, which typically include database connection resources, JMS queue resources, and so on. The acid (atomicity, consistency, isolation, persistence) properties of a transaction are also for the resources it manages. A global variable in the previous question, which can be said to be a piece of storage space in memory, how can the data in memory have the persistence in the transaction attribute? Obviously it is not within the jurisdiction of the transaction and will not be rolled back with the rollback of the transaction.
Second, when to roll back the transaction
In a bean management transaction for JDBC transactions and EJBS, we typically control the rollback of a transaction in the following manner. In the event of some kind of exception, we can control the rollback of the transaction and, of course, commit the transaction.
Connection cn = ...
cn.setAutoCommit(false);
Statement stmt = cn.createStatement();
try{
stmt.executeUpdate("update Order...");
cn.commit();
}catch(Exception e) {
cn.rollback(); //出现异常,回滚当前事务
}finally{
stmt.close();
cn.close();
}
But for EJB container-managed transactions or spring's declarative transactions, it's not the same. For example:
Connection cn = ...
cn.setAutoCommit(false);
Statement stmt = cn.createStatement();
try{
stmt.executeUpdate("update Order...");
cn.commit();
}catch(Exception e) {
cn.rollback(); //出现异常,回滚当前事务
}finally{
stmt.close();
cn.close();
}