1. Examples of usage scenarios
Before we understand how @Transactional is used, we must first know what @Transactional is useful. Let me give you a thumbs up: For example, there are many members in a department, and these two are stored in the department table and the member table respectively. When deleting a certain department, suppose we delete the corresponding members by default. However, this may occur during execution. We first delete the department and then delete the members. However, the department has successfully deleted it, and an exception occurred when deleting the members. At this time, we hope that if the member deletion fails, the previously deleted department will also cancel the deletion. This scenario can be rolled back using @Transactional things.
2. Checked exception and unchecked exception
The reason why we let everyone know the concepts of checked exceptions and unchecked exceptions is that:
Spring uses declarative transaction processing. By default, if an unchecked exception occurs in the annotated database operation method, all database operations will be rollback; if the exception occurs is a checked exception, the database operations will still be submitted by default.
Checked exception:
Invalid, not predictable in the program. For example, invalid user input, file does not exist, network or database link errors. These are all external reasons and are not controlled by the program.
Must be handled explicitly in the code. For example, try-catch block processing, or throw the exception to the previous layer of the call stack with the throws description.
Inherited from java.lang.Exception (except java.lang.RuntimeException).
unchecked exception:
Indicates an error, the logic of the program is wrong. It is a subclass of RuntimeException, such as IllegalArgumentException, NullPointerException and IllegalStateException.
There is no need to explicitly catch unchecked exceptions in the code for processing.
Inherited from java.lang.RuntimeException (and java.lang.RuntimeException inherits from java.lang.Exception).
Looking at the abnormal structure diagram below, it may be more layered:
3. Example of use of @Transactional
This example uses eclipse+maven. Maven is only managed as a jar, and even ape friends of maven who don’t understand can understand it.
3.1. Spring configuration file
The tx namespace must be configured first as follows:
In order to use @Transactional-based transaction management, the following configuration is required in Spring:
<bean id="appTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven proxy-target-class="false" transaction-manager="appTransactionManager" />
The blogger's entire spring 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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--Introduce jdbc configuration file --> <bean id="propertyConfigurer"> <property name="locations"> <list> <value>classpath:properties/*.properties</value> <!--If there are multiple configuration files, just continue to add them here--> </list> </property> </bean> <!--Configure data source--> <bean id="dataSource" > <!--Configure properties--> <!--Configure properties--> <!--Configure properties--> <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/learning" /> <property name="username" value="root" /> <property name="password" value="christmas258@" /> --> <!-- Use properties to configure --> <property name="driverClassName"> <value>${jdbc_driverClassName}</value> </property> <property name="url"> <value>${jdbc_url}</value> </property> <property name="username"> <value>${jdbc_username}</value> </property> <property name="password"> <value>${jdbc_password}</value> </property> </bean> <bean id="appTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven proxy-target-class="false" transaction-manager="appTransactionManager" /> <!-- Automatically scan all mapper interface files corresponding to XxxxMapper.xml, so that you don’t need to manually configure the Mpper mapping one by one. As long as the Mapper interface class and the Mapper mapping file correspond to each other. --> <bean> <property name="basePackage" value="com.luo.dao" /> </bean> <!-- Configure Mybatis file, mapperLocations configure **Mapper.xml file location, configLocation configure mybatis-config file location--> <bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model" /> --> </bean> <!-- Automatically scan annotated beans --> <context:component-scan base-package="com.luo.service" /></beans>3.2. Use @Transactional to add annotations to the user implementation class method
@Transactional(propagation=Propagation.REQUIRED)public void addUser(User user) { userDao.addUser(user); String string = null; if(string.equals("")) { int i = 0; }}In the above method, I deliberately made it have a null pointer exception and things will roll back
3.3. Run the unit test class
@Test public void addUserTest(){ User user = new User(); user.setUserName("luoguohui1"); user.setUserPassword("luoguohui1"); userService.addUser(user);}I found that it could not be inserted, but if @Transactional is removed, the code is as follows. Although an exception occurs, there are still corresponding data added to the database:
3.4. Source code download
Download the final source code of this article: first_maven_project_jb51.rar
4. Concepts that @Transactional in Spring must be understood
@Transactional in Spring is based on the dynamic proxy mechanism and provides a transparent transaction management mechanism to facilitate and quickly solve problems encountered in development.
Generally, it is to comment methods or interfaces or classes through the following code:
@Transactional(propagation=Propagation.NOT_SUPPORTED)
Propagation supports 7 different propagation mechanisms:
REQUIRED: If a transaction exists, the current transaction is supported. If there is no transaction, a new transaction is started.
SUPPORTS: If a transaction exists, the current transaction is supported. If there is no transaction, the execution of the non-transaction. However, for transaction synchronization transaction managers, PROPAGATION_SUPPORTS is slightly different from not using transactions.
NOT_SUPPORTED: Always execute non-transactionally and suspend any existing transaction.
REQUIRESNEW: Always start a new transaction. If a transaction already exists, the existing transaction is suspended.
MANDATORY: If a transaction already exists, support the current transaction. If there is no active transaction, an exception is thrown.
NEVER: Always execute non-transactional, if an active transaction exists, an exception is thrown
NESTED: If an active transaction exists, it runs in a nested transaction. If there is no active transaction, press the REQUIRED property to execute.
Here are some things to note, which must be read, otherwise, if you encounter various pitfalls, the blogger has not reminded you:
Here are some things to note, which must be read, otherwise, if you encounter various pitfalls, the blogger has not reminded you:
Here are some things to note, which must be read, otherwise, if you encounter various pitfalls, the blogger has not reminded you:
Add @Transactional annotation where transaction management is required. @Transactional annotations can be applied to interface definitions and interface methods, class definitions and public methods of classes.
@Transactional annotations can only be applied to methods with public visibility. If you use @Transactional annotation on protected, private, or package-visible methods, it will not report an error, but this annotated method will not display the configured transaction settings.
Note that the occurrence of the @Transactional annotation is not enough to enable transaction behavior, it is just a kind of metadata. The configuration element must be used in the configuration file to truly enable transaction behavior.
Controls whether an interface-based or class-based proxy is created through the element's "proxy-target-class" attribute value. If the "proxy-target-class" genre value is set to "true", then the class-based proxy will work (this is required to cglib.jar in CLASSPATH). If the "proxy-target-class" genre value is set to "false" or this property is omitted, then the standard JDK interface-based proxy will work.
The Spring team recommends using @Transactional annotation on specific classes (or methods of classes) rather than on any interfaces that the class wants to implement. Using the @Transactional annotation on an interface will only take effect when you set up an interface-based proxy. Because annotations cannot be inherited, this means that if a class-based proxy is being used, the transaction settings will not be recognized by the class-based proxy, and the object will not be wrapped by the transaction proxy.
@Transactional's transaction is enabled, either an interface-based or a class-based proxy is created. So in the same class, one method calls another method with transactions, the transaction will not work.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.