Spring article with you in simple terms the principle of affairs

The basic principle Spring affairs

Spring is in fact the nature of the transaction database support for transactions, no transaction database support, spring is unable to provide transaction capabilities. For pure JDBC database operation, you want to use the services, you can follow these steps:

  1. Obtaining a connection Connection con = DriverManager.getConnection ()
  2. Open transaction con.setAutoCommit (true / false);
  3. Perform CRUD
  4. Commit the transaction / rollback transaction con.commit () / con.rollback ();
  5. Close the connection conn.Close ();

After using Spring's transaction management capabilities, we can no longer write code in step 2 and 4, but is done automatically by Spirng. So how Spring open after transaction before we write and CRUD and closing of the session it? To solve this problem, it can be understood Spring's transaction management principles to achieve a whole. Under the following briefly introduced an example embodiment annotations

  1. Open the configuration file annotation drive, on the relevant classes and methods @Transactional identifying annotations.
  2. spring when it starts to parse will generate relevant bean, this time will have to view the classes and methods related notes, and generate a proxy for these classes and methods, and configuration parameters based on the injection @Transaction, thus the agent for us to dispose of matters related to the (open normal commit the transaction, the transaction is rolled back abnormal).
  3. The real transaction commit and rollback database layer is achieved through the binlog or redo log.

Spring's transaction mechanism

All data access technologies have transaction processing, these techniques provides an API to enable the transaction, the transaction is committed to the completion of data manipulation, data or rolled back when the error occurred.

The Spring's transaction mechanism with a unified mechanism to handle transaction processing different data access technologies. Spring's transaction mechanism provides a PlatformTransactionManager interfaces, different transactions using different data access technology interface, as shown in Table.

Data Access Technology and Implementation

 

 

Code defines the transaction manager in the program are as follows:

@Bean 
public PlatformTransactionManager transactionManager() { 

    JpaTransactionManager transactionManager = new JpaTransactionManager(); 
    transactionManager.setDataSource(dataSource()); 
    return transactionManager; 
}

 

Fame transaction

Spring reputation transaction support, users can select the method requires the use of a transaction using annotations, which uses @Transactional annotation on the method shows that this method requires transaction support. This is a realization of AOP-based operation.

@Transactional 
 public  void saveSomething (ID Long, String name) { 
     // database operations 
}

 

Of particular note here is that this @Transactional comment from org.springframework.transaction.annotation package instead javax.transaction.

Two kinds of AOP proxy implementation:

  • jdk is the agent interface, private methods must not exist in the interface, it will not be intercepted;
  • cglib is a subclass, private method still does not appear in the subclass, it can not be intercepted.

Java dynamic proxy.

In particular the following four steps:

  1. InvocationHandler by implementing the interface to create your own call processor;
  2. To create a dynamic proxy class by specifying a set of interface objects and ClassLoader as Proxy class;
  3. Dynamic proxy class constructor is obtained by reflection, the only parameter type is a call processor interface type;
  4. By creating dynamic proxy class instance constructor object configured to call the handler is passed as a parameter.

GCLIB agent

cglib (Code Generation Library) is a powerful, high-performance, high-quality Code generation libraries. It can be extended at runtime Java classes and implement Java interfaces.

  • cglib encapsulates asm, dynamically generate a new class (subclass) at runtime.
  • cglib for AOP, jdk the proxy must be based interfaces, cglib do not have this limitation.

The principle of distinction:

java dynamic proxy using reflection to generate an anonymous proxy class that implements the interface call InvokeHandler before calling a specific method to process. The dynamic proxy cglib asm using open source packages, class files proxy object classes loaded in, processed by modifying a subclass bytecode.

  1. If the target object implements the interface, it will use JDK dynamic proxy AOP implementations default
  2. If the target object implements the interface, you can force the use of CGLIB achieve AOP
  3. If the target object does not implement the interfaces must be used CGLIB library, spring will automatically between JDK dynamic proxies and convert CGLIB

If the class is not a direct method to go inside agency, this time by maintaining its own instance of a proxy.

@Service
 public  class PersonServiceImpl the implements PersonService { 
    @Autowired 
    PersonRepository PersonRepository; 

    // inject their own proxy object, call the transaction in this class inside the method of transfer will not take effect 
    @Autowired 
    PersonService selfProxyPersonService; 

    / ** 
     * transfer test transaction 
     * 
     * @ param Person 
     * @return 
     * / 
    @Transactional 
    public the Person Save (the Person Person) { 
        the Person P = personRepository.save (Person);
         the try {
             // the newly opened independent transaction rollback
            selfProxyPersonService.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            // 使用当前事务 全部回滚
            selfProxyPersonService.save2(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
        personRepository.save(person);

        return p;
    }

    @Transactional
    public void save2(Person person) {
        personRepository.save(person);
        throw new RuntimeException();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void delete() {
        personRepository.delete(1L);
        throw new RuntimeException();
    }
}

 

Spring transaction propagation properties

The spread of so-called spring property transaction is defined when there are multiple simultaneous transactions, the spring should be how to deal with the behavior of these matters. These attributes define TransactionDefinition specific constants explained in the table below:

 

 

Database isolation level

 

 

Dirty read: a transaction data were additions and deletions, but did not submit, another transaction can read uncommitted data. At this time, if the first transaction is rolled back, then the second transaction to attend the dirty data.

Non-repeatable read: have been two read operations in a transaction, between a first read operation and a second operation, a further modified transaction data, this time the two read data are inconsistent.

Magic Reading: the first transaction for a range of data make bulk edits, add a second transaction data in this range, it will be lost when the first transaction to modify the new data.

to sum up:

The higher the isolation level, the more we can ensure the integrity and consistency of the data, but the impact on concurrent performance is also greater.

Most of the database default isolation level is Read Commited, such as SqlServer, Oracle

Few database default isolation level: Repeatable Read for example: MySQL InnoDB

Spring isolation level

 

 

Nested Transactions

By theoretical knowledge of the above bedding, we roughly know some of the properties and characteristics of database transactions and spring affairs, then we analyze some of nested transactions by scene, to in-depth understanding of the mechanism spring transaction propagation.

Suppose the outer transaction Service A Method A () call Service B of the inner Method B ()

PROPAGATION_REQUIRED(spring 默认)

If ServiceB.methodB () level is defined as a transaction PROPAGATION_REQUIRED, then execute ServiceA.methodA () when the spring has played a transaction, then calls ServiceB.methodB (), ServiceB.methodB () to see that they have run ServiceA. internal methodA () transaction, a new transaction is not renewed.

If the time ServiceB.methodB () finds himself running in a transaction not, he will be assigned a transaction for themselves.

Thus, unusual in ServiceA.methodA () or in any place (in) ServiceB.methodB, the transaction will be rolled back.

PROPAGATION_REQUIRES_NEW

For example, we designed the transaction level ServiceA.methodA () transaction level PROPAGATION_REQUIRED, ServiceB.methodB () is PROPAGATION_REQUIRES_NEW.

Then when the execution to ServiceB.methodB (), the transaction ServiceA.methodA () where it will hang, ServiceB.methodB () will play a new transaction, waiting ServiceB.methodB () after the completion of the transaction, it was continue.

He and PROPAGATION_REQUIRED Affairs difference is that the extent of the rollback transaction. Because ServiceB.methodB () is starting a new transaction, so that there are two different matters. If ServiceB.methodB () has been submitted, then ServiceA.methodA () failed rollback, ServiceB.methodB () will not be rolled back. If ServiceB.methodB () fails to roll back, if he throws the exception is () capture ServiceA.methodA, ServiceA.methodA () the transaction may still be submitted (see B major exception thrown is not A will rollback exception) .

PROPAGATION_SUPPORTS

Assuming ServiceB.methodB () transaction level PROPAGATION_SUPPORTS, then when the implementation of ServiceB.methodB (), if found ServiceA.methodA () has opened a transaction, adding the current transaction, if it is found ServiceA.methodA () no open transaction, it is not open affairs. This time, internal affairs are totally dependent on the outermost transaction.

PROPAGATION_NESTED

Now the situation becomes more complicated, ServiceB.methodB () transaction attribute is configured to PROPAGATION_NESTED, how to turn this time collaboration between the two it? ServiceB # methodB If the rollback, then the internal affairs (ie ServiceB # methodB) it will roll back to before execution SavePoint and external affairs (ie ServiceA # methodA) can have the following two approaches:

a, capture abnormal, the abnormality branching logic

void methodA () { 

        the try { 

            ServiceB.methodB (); 

        } the catch (SomeException) { 

            // perform other operations, such as ServiceC.methodC (); 

        } 

    }

In this way also the most valuable parts of nested transactions, which played a branch execution effect, if ServiceB.methodB fails, then execute ServiceC.methodC (), which has been rolled back to SavePoint ServiceB.methodB before it executes, so no dirty data (the equivalent of this method is never executed), this feature can be used in some special services while PROPAGATION_REQUIRED and PROPAGATION_REQUIRES_NEW have no way to do it.

b, external transaction rollback / commit code without making any changes, so if Internal Affairs (ServiceB # methodB) rollback, then roll back to the first ServiceB.methodB SavePoint before it executes (in any case will be so), External Affairs ( that ServiceA # methodA) will decide according to their own specific configuration is commit or rollback

The other three less than basic transaction propagation properties, which is not analysis.

to sum up

For the project need to use the transaction place, I suggest that developers still use spring of TransactionCallback interface to implement the transaction, do not blindly use spring Affairs notes, if we must use annotations, then it must be there for spring Affairs propagation mechanisms and isolation levels a detailed understanding, it will be very unexpected results may occur.

Spring Boot support for transactions

By org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration class. We can see Spring Boot automatically open the annotation support for Spring affairs

Read-only transaction concepts (@Transactional (readOnly = true)) of

  • concept:

From this point of time to set the start (time point a) to the end of this process the transaction, the data submitted by other firms, the transaction will not see! (Query data to others after time a submission does not appear).

@Transcational (readOnly = true) This annotation will normally be written in business class, or on its methods to control its affairs added. When you add in parentheses readOnly = true, it will tell the underlying data source, this is a read-only transaction, for JDBC, the read-only transactions there will be some speed optimization. And write it, other configurations transaction control is the default value, the transaction isolation level (isolation) as DEFAULT, which is followed by isolation level of the underlying data sources, propagation behavior (propagation) the transaction is REQUIRED, so there will still be transaction exists, RuntimeException thrown in the code generation, still cause the transaction to roll back.

  • Applications:
  1. If you execute a single query, it is not necessary to enable transaction support, database support for SQL default read consistency during execution;
  2. If you once execute multiple queries, such as statistical queries, reports, queries, in this scenario, the number of SQL queries must ensure the overall consistency of reading, otherwise, after the previous one SQL query, Article SQL query before the data is other user changes, the Comprehensive statistical queries inconsistent state data read will appear at this time, should enable transaction support.

[Note that perform multiple queries to a certain statistical information, this time in order to ensure overall consistency of the data, use read-only transactions]

Thank you for reading my long-winded, if you think this share to help you, you can help me to the point of a recommendation. There are deficiencies, is also welcome that.

Or you can focus on my public No. [ Java technology zhai ], occasional dry technical content sharing with you redefine the architecture of the charm!

reference: 

http://www.codeceo.com/article/spring-transactions.html 

http://www.cnblogs.com/fenglie/articles/4097759.html

https://www.zhihu.com/question/39074428/answer/88581202

http://blog.csdn.net/andyzhaojianhui/article/details/51984157

Guess you like

Origin www.cnblogs.com/lfs2640666960/p/11708130.html