Analysis of difficulties in Spring advanced transaction management

Source: Internet
Author: User

Analysis of difficulties in Spring advanced transaction management
1Spring transaction Propagation Behavior

The transaction Propagation Behavior refers to how transactions spread between these methods when multiple transaction methods are called each other. Spring supports 7 transaction propagation Behaviors

PROPAGATION_REQUIRED (add existing transaction)

If no transaction exists, create a transaction. If a transaction already exists, add it to the transaction. This is the most common and default method.

PROPAGATION_SUPPORTS (following environment)

Supports the current transaction. If no transaction exists, it is executed in non-transaction mode.

PROPAGATION_MANDATORY (transaction required)

Use the current transaction. If no transaction exists, an exception is thrown.

PROPAGATION_REQUIRES_NEW (Independent Transaction)

Create a new transaction. If a transaction exists, the current transaction is suspended.

PROPAGATION_NOT_SUPPORTED (non-transaction mode)

The operation is performed in non-transaction mode. If a transaction exists, the current transaction is suspended.

PROPAGATION_NEVER (exclude transaction)

It is executed in non-transaction mode. If a transaction exists, an exception is thrown.

PROPAGATION_NESTED (nested transaction)

If a transaction exists, it is executed in the nested transaction. If no transaction exists, perform a similar operation as PROPAGATION_REQUIRED.

 

The default transaction Propagation Behavior of Spring is PROPAGATION_REQUIRED, which is suitable for the vast majority of cases. Assume that ServiveX # methodX () is working in the transaction environment (that is, all of them are enhanced by Spring transactions). Assume that the program has the following call chain: Service1 # method1 () -> Service2 # method2 ()-> Service3 # method3 (), the three methods of the three service classes work in the same transaction through Spring's transaction propagation mechanism.

If you start a thread in a ServiceA and a () method, execute ServiceB's transaction method B () in the newly created thread (). The transaction methods that perform nested calls in the same thread work in the same transaction. If these nested calling methods work in different threads, the transaction methods under different threads work in independent transactions.

 

2 kinds of data persistence Methods Transaction Management

If you use a high-end ORM Technology (Hibernate, JPA, JDO) and a JDBC technology (Spring JDBC, iBatis) is the encapsulation of the latter Connection. Spring will "intelligently" the session of the former in the same transaction thread to encapsulate the Connection of the latter. Therefore, we only need to directly use the Transaction Manager of the former. The following table shows the Transaction Manager corresponding to the hybrid Data Access Technology:

1. Transaction consistency in different persistent Modes

 

Spring provides a tool class for getting bound data connections from the current transaction context, that is, DataSourceUtils. Spring emphasizes that you must use the DataSourceUtils tool class to obtain data connections.

 

Static Connection doGetConnection (DataSource dataSource)

First, try to get the connection from the transaction context, and then get the connection from the data source after the failure;

Static Connection getConnection (DataSource dataSource)

The doGetConnection method has the same function. In fact, it calls the doGetConnection method internally to obtain the connection;

Static void doReleaseConnection (Connection con, DataSource dataSource)

Release the connection and put it back in the connection pool;

Static void release Connection (Connection con, DataSource dataSource)

Like the doReleaseConnection method, in fact, it calls the doReleaseConnection method internally to obtain the connection;

Test demo:

@Servicepublic class TestTranscationServiceImpl implements TestTranscationService {    @Autowired    private TestTranscationDao testTranscationDao;    @Override    @Transactional    public int test(){        testTranscationDao.update1();        testTranscationDao.update2();               return 0;    }}

 

@ Autowired private JdbcTemplate jdbcTemplate; @ Override public int update1 () {// 1. obtain the database Connection con = ceceutils. getConnection (jdbcTemplate. getDataSource (); try {con. prepareStatement (update grade_info set grade_name = '11' where grade_id1_12.16.exe cuteUpdate ();} catch (SQLException e) {throw new RuntimeException (e );} finally {// 2 if there is no context transaction management for the current method and the database connection is not released, the database connection will be leaked // if there is a context transaction, there is no problem with calling or not calling the database connection to release DataSourceUtils. releaseConnection (con, jdbcTemplate. getDataSource () ;}return 0 ;}@ Override public int update2 () {// 3. the database Connection obtained from database Connection 1 is the same Connection con = performanceutils. getConnection (jdbcTemplate. getDataSource (); try {// 4. the database Connection obtained in this method is different from the database Connection obtained in 1 and 3. conn = jdbcTemplate. getDataSource (). getConnection (); conn. close ();} catch (SQLException e) {e. printStackTrace ();} return jdbcTemplate. update (update grade_info set grade_name = 'high school grade 3 'where grade_id = 1 );}

 

Spring provides a tool class for each data access technical framework to obtain the data connection (or its derivatives) bound to the transaction context and a proxy class for the data source (or its derivatives.

 

Considerations for hybrid use of 2Hibernate and JDBC

For the reason of Hibernate level-1 cache, when you operate data using methods such as save, update, delete, and so on, no SQL is actually sent to the database. Only when flush () is called, hibernate will synchronize the status changes in the first-level cache to the database.

Hibernate's transaction management will automatically call the flush () operation when committing a transaction to synchronize the first-level cache to the database. Then, SQL statements will be generated and sent to the database.

It is because of the above reasons that any mixed use of JDBC and Hibernate may cause loss of updates.

When Hibernate and JDBC are used together, the JDBC operations are not synchronized to the Hibernate cache (level-1 cache and level-2 cache), and The status changes in the Hibernate cache are not perceived by JDBC. Therefore, you must pay special attention to this issue during hybrid use.

Because of the synchronization of transactions in the hybrid Data Access Technology Scheme and the cache is not synchronized, it is best to use Hibernate to complete the read and write operations and use Spring JDBC to complete the read operations. For example, you can use Spring JDBC to perform a brief list query and Hibernate to maintain the queried data. If you want to use both Hibernate and Spring JDBC to read and write data, you must fully consider the problems caused by the Hibernate cache mechanism: You must fully analyze the data maintenance logic and promptly call the flush () to avoid overwriting the changes made by Spring JDBC. When Spring JDBC changes the database, it maintains the Hibernate cache.

3Spring transaction enhancement restrictions

Because Spring transaction management is based on the Interface proxy or dynamic bytecode technology, it implements transaction enhancement through AOP.

For AOP transaction Enhancement Based on interface dynamic proxy, because the interface method is public, the implementation method of the implementation class must be public (not protected or private ), static modifiers cannot be used at the same time. Therefore, you can only use the "public" or "public final" modifier to implement the interface dynamic proxy. Other methods cannot be used by dynamic proxy, so the corresponding method cannot implement AOP enhancement, that is, the Spring transaction cannot be enhanced.

The dynamic proxy Scheme Based on CGLib bytecode is to implement AOP enhancement embedding by dynamically creating subclasses by extending the enhanced classes. Methods Using final, static, and private modifiers cannot be overwritten by the quilt class. Correspondingly, these methods cannot be implemented with AOP enhancement. Therefore, you must pay special attention to the use of these modifiers, so as not to accidentally become a fish in transaction management.

4 Spring transaction management exception capture and transaction rollback

Spring's Transaction Manager only performs exception rollback on unchecked exception. Error, RuntimeException and its subclass are unchecked exception. Other exceptions are checked exception.

If try and catch are used in the service layer to catch exceptions, the exceptions in the sevice layer will be intercepted and cannot be thrown to the Transaction Manager, this creates an illusion for the Transaction Manager, just as the program is running and there is no problem, so it will not roll back the runtimeException.

 


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.