Common problems with Java transaction development

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.