Use Spring transaction management database

JavaWeb throughout the project development, the transaction is the most critical part of the reliability of the network used to develop applications. When an application interacts with back-end resources, the transaction will be used, where the back-end resources including databases, MQ, ERP and so on. The database transaction is the most common type, and we often say that the transaction is a transaction that interact with relational databases in the narrow sense.

Services are divided into local affairs and global affairs. Global transactions, also known as distributed transactions, local transaction when the application is connected to a single database resources affairs, also discussed the main contents of this culture.

First, some basic concepts affairs

Property transactions (ACID):

  • Atomicity
  • consistency
  • Isolation
  • Endurance

Vernacular "transaction"

There are three states of affairs (or a process): begin, commit, rollback .

Suppose there is such a scenario: Zhang and Li have 100, one day, to give Joe Smith Doe switch 10 yuan.

Equivalent to the current micro-channel transfers, Zhang made to John Doe transfers $ 10. There are three states

On top of this there is an example of an inappropriate place is, even when there is no operation that John Doe $ 10, Joe Smith has been reduced $ 10, and this discrepancy affairs, if we pretend that John Doe does not receive or return the $ 10, John's purse as well as micro-channel 100. But there are so many in the micro letter, mutual transfer of people, every transfer is a transaction, it is imperative that we isolate these matters, but it has a different isolation levels (see below)

Transaction isolation level

Isolation Levels description For example
DEFAULT The default isolation level of the underlying database storage
READ_UNCOMMITTED The lowest level of isolation, can not say that it matters, because it allows other transactions to read the data submitted in the future The above example, the John Doe did not even receive the 10 yuan, other people can read to John Doe more than 10 yuan.
READ_COMMITTED The default level for most of the database, it ensures that other transactions can read data from another transaction has submitted Only when John Doe 10 yuan this operation (reception or return), others can see the change in the balance of these two.
REPEATABLE_READ A more stringent than the previous, it ensures that after selecting the data, if other transactions to make changes to this data, you can select the new data. The top is in the transfer process, even if Joe Smith and others to turn $ 10, before the transaction commits, Joe Smith always thought of myself only 100 yuan. But this type, Joe Smith in the transfer process can be found that they have 110 yuan
SERIALIZABLE Serializable, is the most stringent and most reliable isolation level, so that all transactions one by one run The system allows each person to execute a transfer of a transaction, there will not be any mistake (of course, matters here is not only refers to a transfer of this transaction)

Spread type of transaction

Which is the current mechanism and the time the transaction began, the micro-channel transfer between the equivalent of how so many people should be

Types of Communication description
PROPAGATION_REQUIRED If no transaction creates a new transaction, if there is already a transaction, added to the transaction;
PROPAGATION_SUPPORTS Support the current transaction, if no transaction is executed in a non-transactional way;
PROPAGATION_MANDATORY Use the current transaction, if no transaction, throw an exception;
PROPAGATION_REQUIRES_NEW New Transaction, if the current transaction exists, the current transaction is pending;
PROPAGATION_NOT_SUPPORTED Performing an operation to a non-transactional manner, if a current transaction is present, leave the current pending transaction;
PROPAGATION_NEVER To perform non-transactional way, if the current transaction exists, an exception is thrown;
PEOPAGATION_NESTED If the current transaction exists, the transaction is executed within abscond. If no transaction, PROPAGATION_REQUIRED Antilles operation is performed;

Two, Spring affairs in solving problems

Problem solving affairs in Spring two types: declarative transaction and programmatic transaction (not recommended)

Spring in transactional interface is the lowest level PlatformTransactionManager, but only its subclasses we use

public interface PlatformTransactionManager {
    //获取事务状态
    TransactionStatus getTransaction(@Nullable TransactionDefinition var1) throws TransactionException;
	//提交
    void commit(TransactionStatus var1) throws TransactionException;
	//回滚
    void rollback(TransactionStatus var1) throws TransactionException;
}	

The interface with the main and TransactionDefinition TransactionStatus two classes. Interested can look at. This is below its sub class diagram, we use here is DataSourceTransactionManager as transaction management class, regardless of the manner in which the use, PlatformTransactionManager this sub-class interface must have.

1. declarative transaction

  • Use annotations

    Configuration files are as follows:

<!--引入公共的配置文件-->
<import resource="application-context.xml"/>

<!--Spring提供的事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg ref="dataSource"/>
</bean>

<!--
    开启事务注解
    这里有个小技巧,如果你的事务管理bean名不是transactionManager
    就要给这个标签配置transaction-manager来指定
    -->
<tx:annotation-driven/>

<!--    配置spring扫描注解注入service类-->
<context:component-scan base-package="cn.lyn4ever.service"/>

Then add this @Transactional annotation on a class or method can

@Transactional
public void insertOne(){
    Store store  =new Store();
    store.setTitle("华为P30");
    storeMapper.insertOne(store);

    int j = 10/0;//指定报错,让事务回滚
}
  • Use AOP configuration

Use aop, we only need to be configured, you can write without any intrusion into our business code. If AOP knowledge is not very understanding, can refer to my previous tutorial series AOP Spring study notes , AOP also has a variety of configurations, where the direct use of the aop namespace

<import resource="application-context.xml"/>

<!--Spring提供的事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg ref="dataSource"/>
</bean>

<tx:advice id="txAdvice">
    <tx:attributes>
        <!-- 对单独方法配置属性-->
        <tx:method name="insert*" rollback-for="java.lang.Exception"/>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:pointcut id="serviceTrans" expression="execution(* cn.lyn4ever.serviceaop.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceTrans"/>
</aop:config>

<!--    配置spring扫描注解注入service类-->
<context:component-scan base-package="cn.lyn4ever.serviceaop"/>
  • Contrast the above two ways:
    • Use annotations can be more fine-grained control, because not all service methods require affairs. Oriented Programming using AOP used, large quantities can be controlled, but are generally in the service layer into the cut.
    • Use annotations words, simple configuration, AOP something slightly more complicated configuration.
    • If it is a new project, the proposal from the outset to use annotation type development. If the transaction is not used (generally mature programmer would not be so dry) project before the change, or without being able to modify the source code, building use AOP.
    • Personal experience, it is recommended to use annotations development, flexibility to configure each method and class. AOP use it, sometimes it is not convenient debugging, if you debug the contents across a service method, will enter aop notification method, a lot of trouble.

2. programmatic transaction

As the name suggests, it is to write directly in the operation of its services business code, so the easiest to do, but most do not recommend. There are two ways, one example is to PlatformTransactionManager injected into the bean, to use it. Another is to use TransactionTemplate Spring provides us. Here directly use the second, this time, we only need to use Spring and transactionManager of injecting these two classes, but in order not to confuse the previous configuration and, I direct a new two objects, that is, the use of programmatic transaction , only these two objects is enough, do not need any other configuration-related matters, only one data source

@Autowired
private DataSource dataSource;

@Test
public void fun() {
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
    //设置数据源,这个数据源的bean是由Spring提供的
    transactionManager.setDataSource(dataSource);
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.execute(txStatus -> {
        Store store = new Store();
        store.setTitle("小米11");
        storeMapper.insertOne(store);
        //制造错误,让事务回滚
        int i = 10 / 0;
        return null;
    });
}

Focus on micro-channel public number "small fish and Java", Spring get the code reply address and more learning materials

Guess you like

Origin www.cnblogs.com/Lyn4ever/p/12640311.html