Spring Transaction Series-Programming transaction __ Programming

Source: Internet
Author: User
Tags commit rollback
What is a transaction?

Database transaction (abbreviation: Transaction) is a logical unit in the execution process of database management system, which consists of a limited database operation sequence.

A transaction should have 4 properties: atomicity, consistency, isolation, persistence, and these four properties are often called acid properties.
* Atomicity (atomicity): The transaction is executed as a whole, and the operations contained therein are either all executed or not executed.
* Consistency (consistency): transactions should ensure that the state of the database transitions from one consistent state to another consistent state. The meaning of a consistent state is that the data in the database should satisfy the integrity constraints.
* Isolation (Isolation): When multiple transactions are executing concurrently, the execution of one transaction should not affect the execution of other transactions.
* Persistence (Durability): Committed transaction modifications to the database should be persisted in the database. isolation level of a transaction

In the database operation, in order to effectively guarantee the correctness of the concurrent read data, the transaction isolation level is proposed. Our database locks are also available to build these isolation levels.

Isolation Level Dirty Reads (Dirty read) non-repeatable read (nonrepeatable Read) Phantom Read (Phantom Read)
Unread (Read UNCOMMITTED) possible possible possible
Read submitted (committed) No way possible possible
REPEATABLE READ (Repeatable Read) No way No way possible
Serializable (Serializable) No way No way No way

Description
* READ UNCOMMITTED (READ UNCOMMITTED): Allow dirty reads, that is, data that could be read to uncommitted transaction modifications in other sessions
* Read Committed: Only the data that has been submitted has been read. Most databases, such as Oracle, are at this level by default (not repeating)
* Repeatable Read (repeated read): Repeatable read. Queries within the same transaction are all consistent at the beginning of the transaction, InnoDB the default level. In the SQL standard, this isolation level eliminates non-repeatable reads, but there are also phantom reads
* Serial Read (Serializable): Fully serialized read, each read requires a table-level shared lock, read and write each other will block

Read uncommitted This level, the database is generally not used, and any operation is not locked, this is not discussed here. The default transaction isolation level for MySQL is repeatable read (repeated read). one, programming transactions

Before Spring appeared, programmatic transaction management was the only option for developers. Everyone familiar with Java JDBC knows that we need to explicitly call connection's Setautocommit (), commit (), rollback () and other transaction management-related methods in code, which is programmatic transaction management. 1. JDBC Programming Transaction Management

public void Save (user user) throws sqlexception{
    Connection conn = Datasource.getconnection ();
    Conn.setautocommit (false);
    try {
        PreparedStatement PS = conn.preparestatement ("INSERT into User (Name,age) value (?,?)");
        Ps.setstring (1,user.getname ());
        Ps.setint (2,user.getage ());
        Ps.execute ();
        Conn.commit ();
    } catch (Exception e) {
        e.printstacktrace ();
        Conn.rollback ();
    } finally{
        conn.close ();
    }
}
2. Hibernate's programmatic transaction management

Hibernate requires explicit invocation of BeginTransaction (), commit (), rollback (), and other transaction management-related methods, as follows:

public void Save (user user) {
    session session = Hibernatedao.opensession ();
    Transaction tx = NULL;
    try {
        tx = Session.begintransaction ();  
        Session.save (user);  
        Tx.commit ();  
    } catch (Exception e) {
        if (tx!=null) {
            tx.rollback ();
        }
    } finally{
        session.close ();
    }
}
3. MyBatis Programming Transaction Management

In MyBatis, we can manage related methods through Org.apache.ibatis.session.SqlSession's commit (), rollback (), and the code is as follows:

    String resource = "Org/mybatis/example/mybatis-config.xml";
    InputStream in = Resources.getresourceasstream (Resource);
    Sqlsessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). build (in);

    sqlsession session = Sqlsessionfactory.opensession (false); Open session, transaction start  
    try {  
        Iusermapper mapper = Session.getmapper (iusermapper.class);  
        User user = new User (9, "Test transaction");  
        int affectedcount = mapper.updateuser (user); The commit statement was not executed because of a subsequent exception  
        user user = new User ("Test transaction continuously");  
        int affectedCount2 = Mapper.updateuser (user2); The commit statement was not executed because of a subsequent exception  
        int i = 2/0;//Trigger Run-time exception  
        session.commit ();//commit session, transaction commit  
    } catch (Exception e) {
  session.rollback (); Rollback
    } finally {  
        session.close ();//close session, free resources  
    }  
References

Distributed Transaction Series (1.2) Spring's transaction architecture: HTTPS://YQ.ALIYUN.COM/ARTICLES/39046?SPM=5176.100239.BLOGCONT39044.27.MMXVHW

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.