Springboot MyBatis Transaction Management

Source: Internet
Author: User
Tags throwable

This article mainly describes the declarative transaction management mechanism provided by Springboot.

First, some concepts

Declarative transaction management is based on AOP and can be supported by @transactional annotations in Springboot, which has the advantage of:

1) non-intrusive, business logic is not contaminated by transaction management code.

2) transaction rollback at the method level, the granularity of the method can be conformed to the transaction management of various business scenarios.

This article uses the most commonly used MyBatis framework to configure the Springboot transaction management mechanism. Below is the introduction to the configuration method.

Second, Springboot mybatis transaction configuration

1. Take a look at Pom dependency

which

1) <parent></parent> tags introduced springboot parent dependency

2) The spring and MyBatis integration packages are used to integrate spring and MyBatis

3) MySQL Database driver package

4) Serialization Support Fastjson

    <Parent>        <groupId>Org.springframework.boot</groupId>        <Artifactid>Spring-boot-starter-parent</Artifactid>        <version>1.4.3.RELEASE</version>    </Parent>    <Dependencies>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-web</Artifactid>        </Dependency>        <Dependency>            <groupId>Org.mybatis.spring.boot</groupId>            <Artifactid>Mybatis-spring-boot-starter</Artifactid>            <version>1.1.1</version>        </Dependency>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-jdbc</Artifactid>        </Dependency>        <Dependency>            <groupId>Mysql</groupId>            <Artifactid>Mysql-connector-java</Artifactid>        </Dependency>        <Dependency>            <groupId>Com.alibaba</groupId>            <Artifactid>Fastjson</Artifactid>            <version>1.2.19</version>        </Dependency>    </Dependencies>

2, Application.properties

This configuration is mainly to implement the configuration MyBatis data source, which is beyond the scope of this article, you can refer to this blog. Http://www.cnblogs.com/kangoroo/p/7133543.html

# main data Source Moonlightspring.datasource.moonlight.driverClassName = Com.mysql.jdbc.driverspring.datasource.moonlight.url=jdbc:mysql://10.93.84.53:3306/moonlight?useunicode=true  &characterencoding=utf-8&zerodatetimebehavior=converttonull& Transformedbitisboolean=true&autoreconnect=true&failoverreadonly= Falsespring.datasource.moonlight.username = Rootspring.datasource.moonlight.password = 1234spring.datasource.moonlight.poolmaximumactiveconnections= 400spring.datasource.moonlight.poolmaximumidleconnections= 200spring.datasource.moonlight.poolmaximumcheckouttime=20000

You can then write the mapper, which is the DAO layer code, based on the data source you added.

The DAO layer code is not affected by the transaction management, either by using the XML configuration method or by using the annotation implementation method.

3. Service Layer

When designing the service layer, it is reasonable to abstract the content that the method contains.

The method is then annotated with @trasactional annotations, which, by default, triggers all database operations in the method to roll back when the Exception.class exception is thrown, which is, of course, the increment, delete, or change.

Of course, @Transational method is available with parameters, the specific parameters are explained as follows:

 
Properties type Description
Value String Optional qualifier descriptor, specifying the transaction manager to use
Propagation Enum:propagation Optional transaction propagation behavior settings
Isolation Enum:isolation Optional Transaction ISOLATION Level setting
ReadOnly Boolean Read-write or read-only transactions, default read and write
Timeout Int (in seconds granularity) Transaction time-out time setting
Rollbackfor Class object array, must inherit from Throwable An array of exception classes that cause transaction rollback
Rollbackforclassname Class An array group, must inherit from Throwable An array of exception class names that caused the transaction rollback
Norollbackfor Class object array, must inherit from Throwable An array of exception classes that will not cause the transaction to be rolled back
Norollbackforclassname Class An array group, must inherit from Throwable An array of exception class names that will not cause the transaction to be rolled back

Give some sample code

@Service Public classGeofenceservice {@AutowiredPrivateMoonlightmapper Moonlightmapper; @Transactional Public intaddgeofence (GeoFence GeoFence) {String formattime=Timefunction.transtimetoformatperfect (System.currenttimemillis ());        Geofence.setcreatetime (Formattime);        Geofence.setupdatetime (Formattime); returnMoonlightmapper.insertone (geoFence); } @Transactional Public intBatchgeofence (list<geofence>geofencelist) {String Formattime=Timefunction.transtimetoformatperfect (System.currenttimemillis ());  for(GeoFence geofence:geofencelist) {geofence.setcreatetime (formattime);        Geofence.setupdatetime (Formattime); }        returnMoonlightmapper.insertbatch (geofencelist); }}

4. Open the transaction

Finally you have to turn on transaction management in the application class, it's easy to turn on transaction management, just @enabletransactionmanagement annotations.

@EnableTransactionManagement @springbootapplication  Public class WebApplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (WebApplication. class , args);}    }

Three, test

You can do a simple test, throw an exception, and test to see if it really guarantees transactional.

After the insert is executed, manually throwing a null pointer exception, you can see that the data is really rolled back.

@Service Public classGeofenceservice {@AutowiredPrivateMoonlightmapper Moonlightmapper; @Transactional Public intaddgeofence (GeoFence GeoFence) {String formattime=Timefunction.transtimetoformatperfect (System.currenttimemillis ());        Geofence.setcreatetime (Formattime);        Geofence.setupdatetime (Formattime); intCount =Moonlightmapper.insertone (geoFence); String a=NULL; A.indexof (C); returncount; }}

Springboot MyBatis Transaction Management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.