Transaction processing in Spring
question answering
1. What is a transaction
speak mysql When a transaction is proposed, a transaction refers to a group sql A collection of statements with multiple entries in the collection sql sentence
It may be insert, update, select, delete or a combination. We hope these multiple sql statements can succeed,
Or both fail. The execution of these sql statements is consistent and executed as a whole.
2. When do you want to use this transaction
When my operation involves multiple tables or multiple sql statements, insert, update, select and delete. Need guarantee
These statements are successful to complete my function, or fail to ensure that the operation meets the requirements.
Bank transfer problem a and B accounts need to be balanced
Now write programs in java code to control transactions. Where should transactions be placed?
On the business method of service class, because the business method will call multiple dao methods and execute multiple sql statements
3. Do you usually use jdbc to access the database or mybatis to access the database? How do you handle transactions
jdbc accesses the database and handles transactions, connection con; conn.commit(); conn.rollback();
mybatis accesses the database and handles transactions, SqlSession.commit();SqlSession.rollback();
hibernate accesses the database, handles transactions, and Sesession.commit();Session.rollback();
4. What are the shortcomings of the transaction handling method in the problem
1) different database access technologies, different transaction objects and methods,
You need to understand how different database access technologies use transactions
2) master the transaction processing logic in multiple databases. When to commit a transaction and when to roll back a transaction.
3) multiple methods of handling transactions.
Summary: it is a variety of database access technologies, with different transaction processing mechanisms, objects and methods.
5. How to solve the problem
In the first mock exam, spring provides a unified model for transaction processing, which can handle transactions of different database access technologies in a unified way.
Using spring's transaction processing mechanism, you can complete the transaction processing of mybatis accessing the database.
Using the transaction processing mechanism of spring, you can complete the transaction processing of hibernate accessing the database.
6. How to handle affairs and what to do
Spring's transaction processing model uses fixed steps. Just provide spring with some information used by transactions
1) spring transaction commit, rollback transaction,
Use the transaction manager object to complete the commit and rollback instead of you
The transaction manager is an interface and implementation class and its many implementation classes.
Interface: PlatformTransactionManager, which defines the important transaction methods commit and rollback
Implementation class: spring has created each database access technology and the corresponding transaction processing class.
mybatis accesses the database - spring creates the data source transaction manager
Hibernate access database - spring creates hibernate transactions manager
How to use: you should tell spring what kind of database access technology you use. How do you tell spring?
Declare the implementation class corresponding to the database access technology, and use the declaration in the spring configuration file
For example, if you want to use mybatis to access the database, you should use it in the xml configuration file
2) What kind of transaction is required by your business method, and describe the type of transaction required.
Describe the transactions required by the method:
1) Isolation level of transaction: there are 4 values
These constants about transactions are defined in the transaction definition interface
These constants are prefixed with ISOLATION_ initial
ISOLATION_xxx
DEFAULT: the DEFAULT transaction isolation level of DB is adopted. MySql defaults to REPEATABLE_READ;
Oracle defaults to READ_COMMITTED:
READ_UNCOMMITTED: read uncommitted. No concurrency issues were resolved.
READ_COMMITTED: read committed. Solve dirty reading, there are non repeatable and unreal reading.
REPEATABLE_READ: repeatable. Solve dirty reading, non repeatable reading and phantom reading.
SERIALIZABLE: serialization. There is no concurrency problem
2) Transaction timeout:
Indicates the longest execution time of a method. If the method exceeds this time, the transaction will be rolled back.
The unit is seconds, integer value, and the default is - 1. TIME_OUT
3) Propagation behavior of transactions
Controls whether business methods have transactions, what kind of transactions they are, and what kind of transactions they are.
Seven propagation behaviors indicate that when your business method is called, the transaction is used between methods.
Transaction PROPAGATION behavior constants are based on PROPAGATION_ Start with the shape of promotion_ XXX
PROPAGATION_REQUIRED
The specified method must be executed within a transaction. If there is a current transaction, it will be added to the current transaction; If there is no current transaction, create a new transaction. This propagation behavior is the most common choice and the default transaction propagation behavior of spring.
If the propagation behavior is added to the doOther() method. If the doSome() method runs in a transaction when calling the doOther() method, the execution of the doOther() method is also added to the transaction. If the doSome() method does not execute within a transaction when calling the doOther() method, the doOther() method creates a transaction and executes it.
PROPAGATION_REQUIRED_NEW
The specified method supports the current transaction, but if there is no current transaction, it can also be carried out in a non transactional manner
PROPAGATION_REQUIRES_NEW
Always create a new transaction. If there is a current transaction, the current transaction will be suspended until the new transaction is executed.
The above needs to be mastered
PROPAGATION_MANDATORY
PROPAGATION_NSSTED
PROPAGATION_NEVER
PROPAGATION_NOT_SUPPORTED
4) the time when the transaction is committed and rolled back
1) when your business method is executed successfully, no exception is thrown. When the method is executed, spring submits the transaction after the method is executed.
2) when your business method throws a runtime exception or Error, spring executes rollback and calls the rollback of the transaction manager
Definition of runtime exception: RuntimeException and its subclasses are runtime exceptions, such as nullpointexception and numberformatecption
3) when your business method throws a non runtime exception, mainly the checked exception, commit the transaction
Checked exception: an exception that must be handled when you write code. For example, IOException,SQLException
Summarize spring transactions
1. Transaction management and its implementation classes are used to manage transactions
The first mock exam of 2.spring is a unified model.
1) specify the implementation class bean of the transaction manager to be used
2) specify which classes and methods need to be added to the transaction function
3) specify the isolation level, propagation behavior and timeout required by the method.
You need to tell spring the class information and method name in your project. Method.
Spring transaction management example
E-commerce purchases goods and creates entity classes
Step0: create database table
Create two database tables, sale and goods
Sales table
The transaction processing scheme he provides in the spring framework
1. Annotation scheme suitable for small and medium-sized projects.
The spring framework uses aop to implement the function of adding transactions to business methods, and uses @ Transactional annotation to add transactions,
The @ Transactional annotation is annotated by the spring framework itself and placed on the top of the public method, indicating that the current method has transactions
You can assign values to the attributes of annotations, indicating the specific isolation level, propagation behavior, exception information, etc
Manage transactions using Spring's transaction annotations (Master)
@Transactional, which can weave transactions into corresponding public methods to realize transaction management.
@All optional properties of Transactional are as follows:
propagation:
Used to set transaction Propagation properties. The attribute type is Propagation enumeration, and the default value is Propagation.required
isolation:
Used to set the isolation level of transactions. The attribute type is isolation enumeration, and the default value is isolation.DEFAULT.
readOnly:
Used to set whether the operation of this method on the database is read-only. This attribute is boolean and the default value is false.
timeout:
Used to set the timeout period for this operation to connect to the database. The unit is seconds, the type is int, and the default value is false.
rollbackFor:
Specify the exception class that needs to be rolled back. The type is Clss [], and the default value is an empty array. Of course, if there is only one exception class, you can not use an array.
rollbackForClassName:
Specify the name of the exception class that needs to be rolled back. The type is String [], and the default value is an empty array. Of course, if there is only one exception class, you can not use array []
noRollbackFor:
Specifies the exception Class that does not need to be rolled back. The type is Class [], and the default value is an empty array. Of course, if there is only one exception Class, you can not use an array.
noRollbackForClassName:
Specifies the name of the exception class that does not need to be rolled back. The type is String [], and the default value is an empty array. Of course, if there is only one exception class, you can not use an array.
Note that @ Transactional can only be used on public methods if it is used on methods. For other non-public methods, if annotations are added@
Transactional, although spring does not report errors. However, the specified transaction will not be woven into the method, because spring will ignore all non-public methods
@Transactional annotation
Steps to use @ Transactional:
1. The transaction manager object needs to be declared
2. Turn on the transaction annotation driver and tell the spring framework that I want to use annotation to manage transactions.
spring will use the aop mechanism to create the proxy object of the class where @ Transactional is located and add transaction functions to the method.
spring adds transactions to business methods:
Before the execution of your business method, start the transaction first, or roll back the transaction after the business method, and use aop's surround notification
@ Around("business method name of the business function you want to add")
Object myAround(){
Start the transaction and spring will start it for you
try{
buy(1001,10);
Transaction management of spring. commit();
}catch(Exception e)
Transaction management of spring. rollback();
}
2. There are many kinds of methods suitable for large projects,
A large number of configuration transactions are required. Use the aspectj framework function to declare the transactions required by classes and methods in the spring configuration file. In this way, the business method and transaction configuration are completely separated.
Implementation steps: all are implemented in the xml configuration file.
1) To use the aspectj framework, you need to add dependencies
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.5</version> </dependency>
2) Declare a transaction manager object
3) The transaction type required by the declaration method (configure the transaction attribute of the method [isolation level, propagation behavior, timeout])
4) Configure aop: specify which types of agents to create from.
Two ways
First:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- Unload the configuration information of the database into an independent file, compile and modify the configuration content of the database spring know jdbc.properties File location --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- Declare data source DataSource,The function is to connect to the database --> <bean id="mydataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- use set Inject into DruidDataSrouce Provide connection database information --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> </bean> <!-- The statement is mybatis Provided in SqlSessionFactoryBean Class, which is created internally SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- set Injection, assigning the data connection pool to dataSource --> <property name="dataSource" ref="mydataSource"/> <!-- mybatis Master profile configLocationResource Property is Resource Type, read configuration file His assignment, using value,Specify the path to the file, using classpath:Indicates the location of the file --> <property name="configLocation" value="classpath:Mybatis.xml"/> </bean> <!-- establish dao Objects, using SqlSession of getMapper(StudentDao.class) MapperScannerConfigurer:Call internally getMapper()Generate each dao Proxy object for interface --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- SqlSessionFactory Object id --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- Specify package name MapperScannerConfigurer It will scan all interfaces in the package and execute each interface once getMapper Method to get the of each interface dao object Created dao Object into spring In the container. dao The default name of an object is the lowercase initial of the interface name --> <property name="basePackage" value="com.sdyu.dao"/><!-- ,Split multiple packages --> </bean> <!-- statement service --> <bean id="buyGoodsService" class="com.sdyu.service.Impl.BuyGoodsServiceImpl"> <property name="saleDao" ref="saleDao"></property> <property name="goodsDao" ref="goodsDao"></property> </bean> <!-- spring transaction processing --> <!-- 1.Claim transaction manager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- Connected database, specifying the data source --> <property name="dataSource" ref="mydataSource"></property> </bean> <!-- 2.Turn on the transaction annotation driver and tell spring To manage transactions using annotations transaction-manager The value of represents the value of the transaction manager object id --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
Second:
<!-- Unload the configuration information of the database into an independent file, compile and modify the configuration content of the database spring know jdbc.properties File location --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- Declare data source DataSource,The function is to connect to the database --> <bean id="mydataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- use set Inject into DruidDataSrouce Provide connection database information --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> </bean> <!-- The statement is mybatis Provided in SqlSessionFactoryBean Class, which is created internally SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- set Injection, assigning the data connection pool to dataSource --> <property name="dataSource" ref="mydataSource"/> <!-- mybatis Master profile configLocationResource Property is Resource Type, read configuration file His assignment, using value,Specify the path to the file, using classpath:Indicates the location of the file --> <property name="configLocation" value="classpath:Mybatis.xml"/> </bean> <!-- establish dao Objects, using SqlSession of getMapper(StudentDao.class) MapperScannerConfigurer:Call internally getMapper()Generate each dao Proxy object for interface --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- SqlSessionFactory Object id --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- Specify package name MapperScannerConfigurer It will scan all interfaces in the package and execute each interface once getMapper Method to get the of each interface dao object Created dao Object into spring In the container. dao The default name of an object is the lowercase initial of the interface name --> <property name="basePackage" value="com.sdyu.dao"/><!-- ,Split multiple packages --> </bean> <!-- statement service --> <bean id="buyGoodsService" class="com.sdyu.service.Impl.BuyGoodsServiceImpl"> <property name="saleDao" ref="saleDao"></property> <property name="goodsDao" ref="goodsDao"></property> </bean> <!-- spring transaction processing --> <!-- 1.Claim transaction manager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- Connected database, specifying the data source --> <property name="dataSource" ref="mydataSource"></property> </bean> <!-- 2.Declare the transaction properties of a business method(Isolation level, propagation behavior, timeout) id Is a custom name that represents<tx:advice>and</tx:advice>Configuration content between transaction-manager: Of the transaction manager object id --> <tx:advice id="myAdvice" transaction-manager="transactionManager"> <!-- Represents the properties of a configuration transaction --> <tx:attributes> <!-- Configure transaction properties for specific methods method There can be more than one name Is the name of the method 1) complete name without package and class. 2)Method can use wildcards,*Represents any character propagation:Propagation behavior, enumeration value isolation="DEFAULT":Isolation level rollback-for="": The specified exception class name. The fully qualified class name must be rolled back if an exception occurs --> <tx:method name="buy" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.NullPointerException,com.sdyu.excep.NotEnoughException"/> <!-- Use wildcards to specify many methods --> <!-- Increase method --> <tx:method name="add*" propagation="REQUIRES_NEW"/> <!-- Modification method --> <tx:method name="modify*" propagation="REQUIRED"/> <!-- Delete method --> <tx:method name="remove*" propagation="REQUIRED"/> <!-- Query method query search find--> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- to configure AOP --> <aop:config> <!-- Configure pointcut expression: specify which classes in the package to use transactions id: The name and unique value of the pointcut expression expression:Pointcut expressions that specify which classes use transactions, aspectj The proxy object is created com.sdyu.service com.crm.service com.service --> <aop:pointcut expression="execution(* *..service..*.*(..))" id="servicePt"/> <!-- Configuring enhancers: associations advice and pointcut advice-ref:Notice, above tx: advice Where is the configuration pointcut-ref: Of pointcut expressions id --> <aop:advisor advice-ref="myAdvice" pointcut-ref="servicePt"/> </aop:config> </beans>
Problems of using Spring in Web projects
1. The javase project has a main method, and the executing code executes the main method,
Container object created in main
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
2. The web project runs on the tomcat server. Once tomcat is started, the project runs all the time.
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>
Configure listener
Create listener ContextLoaderListener
After the listener is created, it will read the default / WEB-INF/applicationContext.xml
Put it in this directory
Modify default directory
contextConfigLocation indicates the path of the file
<context-param> <param-name>contextConfigLocation</param-name> <param-value>Custom path</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
No longer use the ApplicationContext object to create
use
WebApplicationContext ctx =null; obtain ServletContext Container object in. Create a good container object and use it. String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE; Object attr = getServletContext().getArribute(key); if(attr != null){ ctx = (WebApplicationContext)attr; }
Get the container object using the methods in the framework,
ServletContext sc = getServletContext(); ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
Configuration listener: the purpose is to create a container object. Once the container object is created, all objects in the spring.xml configuration file can be created.
Users can use the object directly when they make a request.