Abstract: This article combines the spring source depth analysis to analyze the source code of Spring 5.0.6 version. If there is any description of the error, please correct me.
Directory
First, create a data table structure
Second, create the corresponding data table PO
Iii. Creating mappings between tables and entities
Iv. creating a data manipulation interface
V. Creating a data manipulation interface implementation class
Vi. Creating a Spring configuration file
Seven, testing
The spring declarative transaction frees us from the complexities of transaction processing, so that we no longer have to deal with operations such as getting connections, closing connections, committing transactions, and rolling back, and no longer need to handle the try...catch...finally code in a transaction-related way. While the use of transactions in spring has been relatively straightforward, there are a number of usage and configuration rules, and interested readers can look into the relevant materials themselves for in-depth research, which only lists the most commonly used methods.
Again, we're going to use the simplest examples to visually describe them.
First, create a data table structure
CREATE TABLE`User' (' ID 'bigint( -) not NULLauto_increment, ' username 'varchar( -)DEFAULT NULLCOMMENT'User name', ' password 'varchar( -)DEFAULT NULLCOMMENT'Password', ' sex 'tinyint(1)DEFAULT NULLCOMMENT'user sex, 1: male; 2: Female', ' age 'int(2)DEFAULT NULLCOMMENT'User Age', ' status 'int(1)DEFAULT NULLCOMMENT'user Status, 1: valid; 0: Invalid', ' Create_tm 'timestamp NULL DEFAULT NULLCOMMENT'creation Time', PRIMARY KEY(' id ')) ENGINE=InnoDB auto_increment= - DEFAULTCHARSET=UTF8;
Second, create the corresponding data table PO
Public class User { private Long ID; Private String username; Private String password; Private Integer sex; Private Integer age; Private Integer status; Private Date Createtm; // omit Set/get Method }
Iii. Creating mappings between tables and entities
Public Interface usermapper { int insert (User record); User Selectbyprimarykey (Long ID);}
Iv. creating a data manipulation interface
Public Interface userservice { boolean register (userdto userdto);}
V. Creating a data manipulation interface implementation class
@Service ("UserService") Public classUserserviceimplImplementsUserService {@AutowiredPrivateUsermapper Usermapper; @Override @Transactional (Propagation=propagation.required) Public BooleanRegister (userdto userdto) {if(!objectutils.allnotnull (userdto)) { return false; } User User=NewUser (); Try{beanutils.copyproperties (userdto, user); User.setstatus (1); User.setcreatetm (NewDate ()); }Catch(beansexception e) {return false; } Booleanret = Usermapper.insert (user) = = 1; //transaction test, plus this code, the data is not saved to the database Throw NewRuntimeException ("Insert Error"); returnret; }}
Vi. Creating a Spring configuration file
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:tx= "Http://www.springframework.org/schema/tx"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sp Ring-beans.xsd Http://www.springframework.org/schema/tx HTTP://WWW.SPR Ingframework.org/schema/tx/spring-tx.xsd "> <!--Configure the data source - <BeanID= "DataSource"class= "Com.alibaba.druid.pool.DruidDataSource"Init-method= "Init"Destroy-method= "Close"Lazy-init= "true"> < Propertyname= "Driverclassname"value= "${jdbc.driverclassname}"/> < Propertyname= "url"value= "${jdbc.url}"/> < Propertyname= "username"value= "${jdbc.username}"/> < Propertyname= "Password"value= "${jdbc.password}"/> <!--Configure connection pool initialization size, minimum, maximum - < Propertyname= "InitialSize"value= "${jdbc.initialsize}"/> < Propertyname= "Minidle"value= "${jdbc.minidle}"/> < Propertyname= "Maxactive"value= "${jdbc.maxactive}"/> <!--Configure the time to get the connection wait timeout in milliseconds - < Propertyname= "Maxwait"value= "${jdbc.maxwait}"/> <!--How often the configuration interval is detected to detect idle connections that need to be closed, in milliseconds - < Propertyname= "Timebetweenevictionrunsmillis"value= "${jdbc.timebetweenevictionrunsmillis}"/> <!--configures the minimum lifetime of a connection in a pool, in milliseconds - < Propertyname= "Minevictableidletimemillis"value= "${jdbc.minevictableidletimemillis}"/> < Propertyname= "Validationquery"value= "Select 1"/> < Propertyname= "Testwhileidle"value= "${jdbc.testwhileidle}"/> < Propertyname= "Testonborrow"value= "${jdbc.testonborrow}"/> < Propertyname= "Testonreturn"value= "${jdbc.testonreturn}"/> <!--open Pscache, and specify the size of Pscache on each connection - < Propertyname= "Poolpreparedstatements"value= "${jdbc.poolpreparedstatements}"/> < Propertyname= "Maxpoolpreparedstatementperconnectionsize"value= "${jdbc.maxpoolpreparedstatementperconnectionsize}"/> <!--Statistics SQL Filter - < Propertyname= "Proxyfilters"> <List> <Beanclass= "Com.alibaba.druid.filter.stat.StatFilter"> < Propertyname= "Mergesql"value= "true"/> < Propertyname= "Slowsqlmillis"value= "${jdbc.slowsqlmillis}"/> < Propertyname= "Logslowsql"value= "true"/> </Bean> </List> </ Property> </Bean> <BeanID= "TransactionManager"class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager"> < Propertyname= "DataSource"ref= "DataSource"/> </Bean> <Tx:annotation-driven/></Beans>
Seven, testing
public static void main (string[] args) {applicationcontext context = New Classpathxmlapplicationcontext ("Spring/application.xml" = (userservice) context.getbean ("UserService" = new Userdto (); Userdto.setusername ( "Zhang San" 20 1 // save a record Userservice.register (userdto);}
In the previous test example, the Userservicelmpl class implemented the Register function in interface userservice by adding a code that throws an exception: throw new RuntimeException ("Insert Error"). When the code is injected to execute the test class, you will see that the data was successfully saved to the database, but if you run the test class again when you join the code, you find that the operation here does not save the data to the database.
Note: By default, transaction processing in spring only rolls back the RuntimeException method, so if you replace runtimeexception here with a normal exception it will not produce a rollback effect.
Spring Transaction (i) Example of transaction usage in JDBC mode