The use of database transaction in Spring BootSpring Boot

Keywords: Spring Database MySQL JDBC

Hello, welcome to the program workplace, where you need to improve technology, career planning, personal growth, sideline development and other articles.

Learn and improve with more small partners.

This is the twelfth article in the Spring Boot series. Understanding the previous articles will help you better understand this article:

1.Spring Boot (I) get to know the spring Boot framework
2.Spring Boot (2) basic configuration of spring Boot
3.Spring Boot (3) principle of automatic configuration of Spring Boot
4.Spring Boot (4) Spring Boot web project development
5.Spring Boot (V) Spring Boot web development project (2) configuration
6.Spring Boot (6) SSL configuration for spring Boot web development
7.Spring Boot (7) Spring Boot Websocket
8.Spring Boot (8) Spring Boot Websocket realizes chat function
9.Spring Boot (IX) use of spring Boot Bootstrap and AngularJS
10.Spring Boot (x) using JPA in Spring Boot
11.Spring Boot (XI) using REST resource output in Spring Boot

Preface

(1) . database transactions

(2) Common property sheets for. Transactional annotations

(3) . database transaction use practice

In the previous article, we talked about the use of REST resource output in Spring Boot; in this article, we will continue to introduce the use of database transactions in Spring Boot.

(1) . database transactions

There are two ways to implement Spring declarative things: the first is to configure xml, and the second is to use related annotations

Spring Boot is very simple to use transactions. First, use the annotation @ EnableTransactionManagement to enable transaction support, and then add the annotation @ Transactional to the Service method accessing the database.

For transaction manager, whether JPA or JDBC, it implements self interface PlatformTransactionManager. If you add spring boot starter JDBC dependency, the framework will inject DataSourceTransactionManager instance by default. If you add a spring boot starter data JPA dependency, the framework will inject the jpatractionmanager instance by default.

(2) Common property sheets for. Transactional annotations

Common property sheets that give Transactional annotations:

propagation

The propagation behavior of the transaction. The default value is REQUIRED.

isolation

Isolation degree of transaction, DEFAULT value is DEFAULT

timeout

Timeout of transaction, default value is - 1, no timeout.

If the time-out time (in seconds) is set, the transaction is automatically rolled back if the time limit is exceeded but the transaction has not completed.

read-only

Specifies whether the transaction is read-only, and the default value is false. In order to ignore methods that do not need transactions, such as reading data, you can set read-only to true.

rollbackFor

It is used to specify the exception types that can trigger transaction rollback. If there are multiple exception types that need to be specified, they can be separated by commas. {xxx1.class, xxx2.class,…… }

noRollbackFor

Throw the exception type specified by no rollback for, and do not roll back the transaction. {xxx1.class, xxx2.class,…… }

......

(3) . database transaction use practice
#New Spring Boot project
 

 

 


#Database configuration

We still use mysql database here. We need to add dependency.

<dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <version>5.1.40</version></dependency>

 

#Add database configuration information in the application.properties file

The database configuration is under the project resources directory.

spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/springboottransac?useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=root
spring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.jackson.serialization.indent_output=true

Entity class

Entity class is used to generate data objects and query data

package org.myyoung.cxzc.springboottransaction;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;
@Entitypublic class Person {    @Id    @GeneratedValue    private Long id;    private String name;    private String detail;    private Integer time;    private String writer;
    public Long getId() {        return id;    }
    public void setId(Long id) {        this.id = id;    }
    public String getName() {        return name;    }
    public void setName(String name) {        this.name = name;    }
    public String getDetail() {        return detail;    }
    public void setDetail(String detail) {        this.detail = detail;    }
    public Integer getTime() {        return time;    }
    public void setTime(Integer time) {        this.time = time;    }
    public String getWriter() {        return writer;    }
    public void setWriter(String writer) {        this.writer = writer;    }
    public Person(String name, String detail, Integer time, String writer) {        this.name = name;        this.detail = detail;        this.time = time;        this.writer = writer;    }}

#Create entity class Repository

package org.myyoung.cxzc.springboottransaction;import org.springframework.data.jpa.repository.JpaRepository;
public interface PersonRepository extends JpaRepository<Person,Long> {}
Here we test the use of transaction, so we only use the existing function save in it, and do not add the user-defined database operation function here.

#Business Service

1. Service interface

package org.myyoung.cxzc.springboottransaction;public interface DemoService {    public Person savePersonWithRollBack(Person person);
    public Person savePersonWithoutRollBack(Person person);}

Here we add two service interfaces to test the rollback operation of the transaction.

2. Service implementation

package org.myyoung.cxzc.springboottransaction;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import javax.transaction.Transactional;
@Servicepublic class DemoServiceImpl implements DemoService {    @Autowired    PersonRepository personRepository;
    @Transactional(rollbackOn = {IllegalArgumentException.class})    @Override    public Person savePersonWithRollBack(Person person) {        Person p = personRepository.save(person);        if (person.getName().equals("Procedural workplace")) {            throw new IllegalArgumentException("Program workplace already exists, data will be rolled back");        }        return p;    }
    @Transactional(dontRollbackOn= {IllegalArgumentException.class})    @Override    public Person savePersonWithoutRollBack(Person person) {        Person p = personRepository.save(person);        if (person.getName().equals("Procedural workplace")) {            throw new IllegalArgumentException("Program workplace already exists, but data will not be rolled back");        }        return p;    }}

1. Inject the person bean of the person repository 2. Use the rollbackOn attribute of the @ Transactional annotation to specify the data rollback when a specific exception occurs.
3. Make verification and manual triggering exception
4. Use the dontRollbackOn property of the @ Transactional annotation to specify that the data will not be rolled back when a specific exception occurs.

#Create controller

This is used to verify the rollback operation when the interface is called.

package org.myyoung.cxzc.springboottransaction;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class MyController {    @Autowired    private DemoService demoService;
    @RequestMapping("/norollback")    public Person noRollback(Person person) {        return demoService.savePersonWithoutRollBack(person);    }
    @RequestMapping("/rollback")    public Person rollback(Person person) {        return demoService.savePersonWithRollBack(person);    }}


#Running the project

1. rollback

Enter in browser:
http://localhost:8080/rollback?name = program workplace & time = 8 & detail = focus on the spring boot applet fluent & writer = crawling snail

The effect is as follows:


At this time, the data in the query database is not inserted and has been rolled back

1. no rollback.

Enter in browser:
http://localhost:8080/norollback?name = program workplace & time = 8 & detail = focus on the spring boot applet, fluent & writer = crawling snail
The effect is as follows:


At this time, insert a piece of data in the query database, because there is no rollback.
 

ok, this article is completed here. If buddy still has doubts, we can pay attention to the number of official account plus group.

Reference resources:
1. Spring Boot, the subverter of Java EE development

Download address of this case:

https://github.com/ProceduralZC/itcxzc/tree/master/springboottransaction

 

Add WeChat (mmlz6879), reply to "program workplace" or click "pick me up > plus group" in the lower right corner of official account, and pull you into the discussion group and many small buddy partners who love learning together.

Author: Little dandelion
Official account: procedural workplace
Wechat: mmlz6879
Introduction: focus on Spring Boot, microservice, front-end APP, sideline earning, workplace planning, operation management, personal growth, etc., pay attention to and reply to the learning materials, and get the learning dry goods carefully prepared for you!
A dedicated professional programmer
Data: the dry cargo data that can be acquired by the official account can be returned to the public information system.

72 original articles published, praised by 149 and visited 410000+

Posted by tinkertron on Wed, 26 Feb 2020 05:15:24 -0800