preface:
Hello, guys, I'm running snail rz. Of course, you can call me snail Jun. I'm a rookie who has studied Java for more than half a year. At the same time, I also have a great dream, that is, to become an excellent Java Architect one day.
This Spring basic learning series is used to record the whole process of learning the basic knowledge of Spring framework (this series is written with reference to the latest Spring 5 tutorial of crazy God in station B. because it was sorted out before, but it was not released at that time, there may be errors in some places. I hope you can correct them in time!)
After that, I will update this series at a faster rate day by day. If you haven't learned the spring 5 framework, you can learn from my blog; Of course, the little friends who have studied can also review the basics with me.
Finally, I hope I can make progress with you! Come on! Boys!
No more nonsense. Let's start today's learning content. Today we come to the 14th stop of Spring basic learning: the implementation of Spring transactions!
14.1 implementation of spring transaction
14.1.1 what is the implementation of spring transactions?
The concept of transaction is at the database level. Spring only extends based on transactions in the database and provides some ways for programmers to operate more conveniently
Spring's transaction management is divided into two ways: programmatic transaction management and declarative transaction management
- Programming transaction management: that is to use the transaction template to manage transactions manually. It is generally not used in actual development. Here is an understanding
- Declarative transaction management: it is the defau lt transaction management method of Spring. You need to define the data source (DriverManagerDataSource) and transaction manager (DataSourceTransactionManager) in the configuration file, and then inject the transaction manager into the transaction proxy factory Bean (TransactionProxyFactoryBean) to generate the proxy, or use the Spring AOP XML method (< declarative transaction management based on tx / AOP configuration) or Spring AOP Annotation (i.e. @ Transactional annotation for declarative transaction management)
14.1.2 using TransactionProxyFactoryBean
1. Write MySQL database scripts and introduce related resource dependencies
1-1 writing MySQL database script
-- Create database MyBatis,``Used to prevent and MySQL Keywords conflict Create Database `MyBatis`; -- use MyBatis database Use `MyBatis`; -- Create database tables User Create table `User`( `id` int(10) not null primary key, `name` varchar(30) default null, `pwd` varchar(30) default null )engine=InnoDB default charset=utf8; -- Batch insert some user information Insert into `User`(`id`,`name`,`pwd`) values (1,'Jay Chou','zjl123456'), (2,'Fang Wenshan','fws123456'), (3,'Huang Junlang','hjl123456')
1-2 introducing project related resource dependencies
- The premise is to create a Maven project, and then import the corresponding resource dependencies in the pom.xml file
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-study</artifactId> <groupId>com.kuang</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>spring-10-mybatis</artifactId> <!-- Import resource dependencies --> <dependencies> <!-- mysql Drive resource dependency --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- mybatis resources dependence --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!-- spring resources dependence --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency> <!-- spring To operate the database, you need another one spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.0.RELEASE</version> </dependency> <!-- junit unit testing --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- log4j resources dependence --> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- aop Weaving resource dependency --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <!-- mybatis-spring resources dependence --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.3</version> </dependency> <!-- lombok resources dependence --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> </dependencies> <!-- stay build Medium configuration resources,To prevent the failure of resource export --> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
2. Prepare database configuration file and Mybatis core configuration file
2-1 write db.properties database configuration file
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456
2-2 write the mybatis-config.xml configuration file
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- configuration: Core profile --> <configuration> <!-- Set standard log output --> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!-- Use alias: package the alias --> <typeAliases> <package name="com.kuang.pojo"/> </typeAliases> </configuration>
3. Write User entity class and UserMapper interface
3-1 writing User entity classes
package com.kuang.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data // Introduce parameterless construction, get and set methods and toString methods @AllArgsConstructor // Introducing parametric structure @NoArgsConstructor // The nonparametric structure is introduced again to prevent covering the nonparametric structure when the parametric structure is introduced public class User { private int id; // User number private String name; // user name private String pwd; // password }
3-2 writing UserMapper interface
package com.kuang.mapper; import com.kuang.pojo.User; import java.util.List; public interface UserMapper { // Get all user information public List<User> getUsers(); // Add user information public int insertUser(User user); // Delete user information public int deleteUser(int id); // Modify user information public int UpdateUser(User user); }
4. Write UserMapper.xml mapping file and UserMapperImpl implementation class
4-1 write UserMapper.xml mapping file
- Create the same package path as UserMapper under the resources resource path and store the UserMapper.xml mapping file
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace=Bind a corresponding Dao/Mapper Interface--> <mapper namespace="com.kuang.mapper.UserMapper"> <!-- Query all user information --> <!-- When the alias is wrapped through, resultType(Result type)You can directly use the corresponding entity class name without writing the full class name --> <select id="getUsers" resultType="user"> Select * from mybatis.user </select> <!-- Add user information --> <insert id="insertUser" parameterType="com.kuang.pojo.User"> Insert into mybatis.user(id, name, pwd) values(#{id} ,#{name}, #{pwd}) </insert> <!-- Delete user information --> <delete id="deleteUser" parameterType="int"> Delete from mybatis.user where id = #{id} </delete> <!-- Modify user information --> <update id="UpdateUser" parameterType="com.kuang.pojo.User"> Update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id} </update> </mapper>
4-2 writing UserMapperImpl implementation class
package com.kuang.mapper; import com.kuang.pojo.User; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; public class UserMapperImpl implements UserMapper { // Introduce SqlSessionTemplate object private SqlSessionTemplate sqlSessionTemplate; // Dynamically inject SqlSessionTemplate object using set method public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } // Override getUsers method public List<User> getUsers() { // Get UserMapper object UserMapper userMapper = sqlSessionTemplate.getMapper(UserMapper.class); // Returns the getUsers method of the UserMapper object return userMapper.getUsers(); } }
In order to save space, the UserService class and UserServiceImpl implementation class are not written here
5. Write spring-dao.xml and ApplicationContext.xml configuration files
5-1 write the spring-dao.xml configuration file
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1.Associated database profile --> <context:property-placeholder location="classpath:db.properties"/> <!-- 2.to configure DataSource Data source: read the database configuration file, which is used here Spring Default data source JDBC --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 3.to configure sqlSessionFactory Factory object --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 2.1 quote dataSource data source --> <property name="dataSource" ref="dataSource"/> <!-- 2.2 binding Mybatis Core profile for --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 2.3 Register in core profile Mapper.xml file --> <property name="mapperLocations" value="classpath*:com/kuang/mapper/*.xml"/> </bean> <!-- 4.to configure SqlSessionTemplate Template object --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <!-- Only constructor injection can be used sqlSessionFactory: Because it doesn't set method --> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!-- 5.to configure transactionManager Transaction manager: dependent on dataSource data source --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 6.Generate proxy class(userDaoProxy): Let the agent manage transactions, depending on the transaction management class --> <bean id="userDaoProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <!-- #6.1 provide transaction manager -- > <property name="transactionManager" ref="transactionManager"/> <!-- #6.2 configure target class usermapper -- > <property name="target" ref="userMapper"/> <!-- #6.3 provide UserMapper interface -- > <property name="proxyInterfaces" value="com.kuang.mapper.UserMapper"/> <!-- #6.4 transaction details configuration, assign value to transaction definition object -- > <property name="transactionAttributes"> <props> <!-- Configure all methods of the enhanced target class(*Represents all),And set propagation behavior and isolation level --> <prop key="*">PROPAGATION_REQUIRED,ISOLATION_REPEATABLE_READ</prop> </props> </property> </bean> </beans>
It is used to configure which methods in the target class are enhanced by setting the key attribute in the prop tag
key indicates the method name. If you use "*", it indicates all methods; if you use get *, it indicates methods starting with get
The text text in the prop tag writes the transaction details and transaction definition in a fixed format
- Propagation_required indicates that the current transaction is supported. If not, a new transaction will be created
- Isolation_repeatable_read indicates the repeatable read level, etc. the values are separated by commas
5-2 write ApplicationContext.xml configuration file
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Import in master profile spring-dao.xml configuration file --> <import resource="spring-dao.xml"/> <!-- injection userMapperImpl Implementation class --> <bean id="userMapper" class="com.kuang.mapper.UserMapperImpl"> <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/> </bean> </beans>
6. Test results and summary of advantages and disadvantages
6-1 test results
- Write MyTest test class
package com.kuang.mapper; import com.kuang.pojo.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class MyTest { @Test public void getUsers() { // Read the context information and get the IOC container of Spring ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // Get the Bean information of userDaoProxy proxy proxy object through the IOC container of Spring UserMapper userMapper = (UserMapper) context.getBean("userDaoProxy"); // Call the getUsers method of userMapper. Get all user information, and then traverse for (User user : userMapper.getUsers()) { // Print user information System.out.println(user); } } }
- test result
6-2 summary of advantages and disadvantages
Advantage: you don't need to pay attention to business logic in the code, but leave it to the Spring container for transaction control
Disadvantages: the configuration file is too bloated and difficult to read
14.1.3 using Spring AOP XML
You only need to modify the content of the spring-dao.xml configuration file, which is consistent with the TransactionProxyFactoryBean method used in 12.2.2
1. Modify the spring-dao.xml configuration file
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 1.Associated database profile --> <context:property-placeholder location="classpath:db.properties"/> <!-- 2.to configure DataSource Data source: read the database configuration file, which is used here Spring Default data source JDBC --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 3.to configure sqlSessionFactory Factory object --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 2.1 quote dataSource data source --> <property name="dataSource" ref="dataSource"/> <!-- 2.2 binding Mybatis Core profile for --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 2.3 Register in core profile Mapper.xml file --> <property name="mapperLocations" value="classpath*:com/kuang/mapper/*.xml"/> </bean> <!-- 4.to configure SqlSessionTemplate Template object --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <!-- Only constructor injection can be used sqlSessionFactory: Because it doesn't set method --> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!-- 5.to configure transactionManager Transaction manager: dependent on dataSource data source --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 6.combination AOP Realize transaction weaving: configure transaction notification --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- Configure the transaction for the method, and configure the propagation characteristics of the transaction: propagation --> <tx:attributes> <!-- #1 configure the propagation transaction attribute for the methods of inserting, deleting and modifying users respectively, and its value is required -- > <tx:method name="insert" propagation="REQUIRED"/> <tx:method name="delete" propagation="REQUIRED"/> <tx:method name="update" propagation="REQUIRED"/> <!--#2 set read-only -- > for query user method <tx:method name="select" read-only="true"/> <!-- #3 configure the propagation transaction attribute for all methods (* refers to all methods), and the value is also set to required -- > <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 7.Configure business entry --> <aop:config> <!-- #7.1 set the entry point and enhance all methods of all types of classes under the com.kuang.mapper package and its sub packages -- > <!-- use pointcut: Set the "place" where the aspect notification is executed use expression: Define pointcut expressions, execution(* com.kuang.mapper..*.*(..)) --> <aop:pointcut id="txPointCut" expression="execution(* com.kuang.mapper..*.*(..))"/> <!-- #7.2 execute surround add (combining txadvice with txpointcut) - > <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> </beans>
2. Transaction propagation behavior and pointcut expression
2-1 propagation transaction propagation behavior
Propagation has seven transaction propagation behaviors. The default is REQUIRED
- REQUIRED: supports the current transaction. If there is no current transaction, it is a common choice to create a new transaction
- SUPPORTS: SUPPORTS the current transaction. If there is no transaction, it will be executed in a non physical way
- MANDATORY: supports the current transaction. If there is no transaction, an exception will be thrown
- REQUIRED_NEW: create a new transaction. If there is a current transaction, suspend the current transaction
- NO_SUPPORTED: perform operations in a non transactional manner. If there is a transaction, suspend the current transaction
- NEVER: execute in a non transactional manner. If there is a transaction, an exception will be thrown
- NESTED: supports the current transaction. If the current transaction exists, a NESTED transaction will be executed. If there is no transaction, a new transaction will be created
2-2 expression pointcut expression
pointcut: indicates the entry point, that is, the "place" where the aspect notification is executed
Expression: indicates the expression defining the pointcut, i.e. execution(* com.kuang.mapper... (...))
-
execution(): expression body
-
The first * indicates the return type, and the * indicates all types
-
com.kuang.mapper...: indicates the name of the package to be intercepted. The following two. Signs indicate the current package and all sub packages of the current package
-
The second * sign: indicates the class name, and the * sign indicates all classes
-
(...): the last * sign represents the method name, the * sign represents all methods, the following () represents the parameters of the method, and the two. Signs represent any parameters
3. Test results and use summary
3-1 test results
- Write MyTest test class
package com.kuang.mapper; import com.kuang.pojo.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class MyTest { @Test public void getUsers() { // Read the context information and get the IOC container of Spring ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // Get the Bean information of the UserMapper object through the IOC container of Spring UserMapper userMapper = context.getBean("userMapper", UserMapper.class); // Call the getUsers method of userMapper. Get all user information, and then traverse for (User user : userMapper.getUsers()) { // Print user information System.out.println(user); } } }
- test result
3-2 summary of advantages and disadvantages
- Spring provides a declarative transaction management method based on tx / AOP configuration, which is also one of the most commonly used transaction management methods in practical development
- Compared with the TransactionProxyFactoryBean method, the implementation using Spring AOP XML method is much simpler
14.1.4 using Spring AOP Annotation
1. Modify the spring-dao.xml configuration file
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 1.Associated database profile --> <context:property-placeholder location="classpath:db.properties"/> <!-- 2.to configure DataSource Data source: read the database configuration file, which is used here Spring Default data source JDBC --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 3.to configure sqlSessionFactory Factory object --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 2.1 quote dataSource data source --> <property name="dataSource" ref="dataSource"/> <!-- 2.2 binding Mybatis Core profile for --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 2.3 Register in core profile Mapper.xml file --> <property name="mapperLocations" value="classpath*:com/kuang/mapper/*.xml"/> </bean> <!-- 4.to configure SqlSessionTemplate Template object --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <!-- Only constructor injection can be used sqlSessionFactory: Because it doesn't set method --> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!-- 5.to configure transactionManager Transaction manager: dependent on dataSource data source --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 6.Registration transaction management driver --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
2. Modify UserMapperImpl implementation class
package com.kuang.mapper; import com.kuang.pojo.User; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; public class UserMapperImpl implements UserMapper { // Introduce SqlSessionTemplate object private SqlSessionTemplate sqlSessionTemplate; // Dynamically inject SqlSessionTemplate object using set method public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } // Use @ Transactional annotation to set transaction propagation behavior, isolation level and read-only @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = true) // Override getUsers method public List<User> getUsers() { // Get UserMapper object UserMapper userMapper = sqlSessionTemplate.getMapper(UserMapper.class); // Returns the getUsers method of the UserMapper object return userMapper.getUsers(); } @Override public int insertUser(User user) { // Get UserMapper object UserMapper userMapper = sqlSessionTemplate.getMapper(UserMapper.class); // Returns the insertUser method of the UserMapper object return userMapper.insertUser(user); } @Override public int deleteUser(int id) { // Get UserMapper object UserMapper userMapper = sqlSessionTemplate.getMapper(UserMapper.class); // Returns the deleteUser method of the UserMapper object return userMapper.deleteUser(id); } @Override public int UpdateUser(User user) { // Get UserMapper object UserMapper userMapper = sqlSessionTemplate.getMapper(UserMapper.class); // Returns the UpdateUser method of the UserMapper object return userMapper.UpdateUser(user); } }
3. Write test classes and test results
3-1 writing test classes
package com.kuang.mapper; import com.kuang.pojo.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class MyTest { @Test public void getUsers() { // Read the context information and get the IOC container of Spring ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // Get the Bean information of the UserMapper object through the IOC container of Spring UserMapper userMapper = context.getBean("userMapper", UserMapper.class); // Call the getUsers method of userMapper. Get all user information, and then traverse for (User user : userMapper.getUsers()) { // Print user information System.out.println(user); } } }
3-2 test results
4. Usage Summary
- The @ transactional annotation can be used on the Dao layer or Service layer implementation class to start the transaction. All SQL in each method of addition, deletion, modification and query will be executed in one transaction, that is, they will either succeed or fail
- After adding @ transitional annotation to a method, Spring will generate a proxy object based on this class, which will be used as a Bean
- When using the method of this proxy object, if there is @ transactional annotation on this method, the proxy logic will first set the automatic submission of transactions to false, and then execute the original business logic method
- If there is no exception in the method of executing the business logic, the agent logic will commit the transaction; If there is an exception in executing the business logic method, the transaction will be rolled back
5. Summary of advantages and disadvantages
- Compared with the first two methods, using @ transactional annotation does not need to write cumbersome configuration files related to transactions
- You only need to use the @ transactional annotation, and then configure the transaction propagation behavior and isolation level in the annotation, which improves the development efficiency
Well, this is the end of today's learning about the implementation of Spring transactions. Welcome friends to actively study and discuss. If you like, you can pay attention to Mr. snail. By the way, we'll see you next time. Bye!
Reference video link: https://www.bilibili.com/video/BV1WE411d7Dv([crazy God says Java] the latest tutorial of spring 5, the IDEA version is easy to understand)