Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the SpringBoot transaction mechanism?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "what is the SpringBoot transaction mechanism?", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what is the SpringBoot transaction mechanism" article.

I. the transaction mechanism of Spring

All data access technologies have transaction mechanisms that provide API to open transactions, commit transactions to complete data operations, or roll back data when errors occur.

The transaction mechanism of Spring uses a unified mechanism to deal with transactions of different data access technologies. The transaction mechanism of Spring provides a PlatformTransactionManager interface, and transactions of different data access technologies are implemented using different interfaces:

The code to define the transaction manager in the program is as follows:

@ Bean public PlatformTransactionManager transactionManager () {JpaTransactionManager transactionManager = new JpaTransactionManager (); transactionManager.setDataSource (dataSource ()); return transactionManager;}

II. Declarative transaction

Spring supports declarative transactions, and even if annotations are used to select methods that require transactions, it uses @ Transactional annotations to indicate that the method requires transaction support.

@ Transactional public void saveSomething (Long id, String name) {/ / Database Operation}

It is important to note here that this @ Transactional annotation comes from the org.springframework.transaction.annotation package, not javax.transaction.

Spring provides support for @ EnableTransactionManagement annotations on configuration classes to open declarative transactions. When @ EnableTransactionManagement is used, the Spring container automatically scans the methods and classes annotated with @ Transactional. @ EnableTransactionManagement is used as follows:

@ Configuration @ EnableTransactionManagement public class AppConfig {}

Use @ Transactional at the class level

@ Transactional can be annotated not only on methods, but also on classes. When annotated on a class, it means that all public methods of this class are transactional. If @ Transactional annotations are used at both the class level and the method level, using annotations at the class level overloads the annotations at the method level.

IV. Transaction support of Spring Data JPA

Spring Data JPA enables transaction support for all default methods, and the readOnly=true attribute is enabled by default for query transactions.

As you can see from the source code SimpleJpaRepository, SimpleJpaRepository defines @ Transactional (readOnly=true) at the class level, while the @ Transactional attribute is overridden in the operations related to save and delete, where the readOnly attribute is false, and the rest of the query operation readOnly is still false.

5. Transaction support of Spring Boot

1. Automatically configured transaction manager

When using JDBC as the data access technology, SpringBoot defines the implementation of PlatformTransactionManager for us. The Bean; configuration of DataSourceTransactionManager is defined in the org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration class:

@ Bean @ ConditionalOnMissingBean @ ConditionalOnBean (DataSource.class) public PlatformTransactionManager transactionManager () {return new DataSourceTransactionManager (this.dataSource);}

When using JPA as the data access technology, Spring Boot defines an implementation of PlatformTransactionManager for us. The Bean; configuration of JpaTransactionManager is defined in the org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.class class:

Bean @ ConditionalOnMissingBean (PlatformTransactionManager.class) public PlatformTransactionManager transactionManager () {return new JpaTransactionManager ();}

two。 Support for automatically opening annotated transactions

The class Spring Boot specializes in configuration transactions is: org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, which relies on JpaBaseConfiguration and DataSourceTransactionManagerAutoConfiguration.

Support for declarative transactions is also enabled in the DataSourceTransactionManagerAutoConfiguration configuration, as follows:

@ ConditionalOnMissingBean (AbstractTransactionManagementConfiguration.class) @ Configuration @ EnableTransactionManagement protected static class TransactionManagementConfiguration {}

So in Spring Boot, you don't need to show and turn on the @ EnableTransactionManagement annotation.

VI. Instance (Springboot)

1.pom.xml:

Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-data-rest mysql mysql-connector-java runtime

2.application.yml:

Server: port: 5000 spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 username: root password: password jpa: hibernate: ddl-auto: update # the first summary table create is followed by update show-sql: true

3. Entity class Staff:

@ Entity public class Staff {@ Id @ GeneratedValue private Long id; private String name; private Integer age; private String address; public Staff () {super ();} public Staff (Long id, String name, Integer age, String address) {super (); this.id = id; this.name = name; this.age = age; this.address = address;} / / omit get, set methods}

Repository of 4.Staff:

Public interface StaffRepository extends JpaRepository {}

5. Service Interface:

Public interface StaffService {public Staff saveStaffWithRollBack (Staff staff); / / rollback public Staff saveStaffWithoutRollBack (Staff staff); / / No rollback}

6. Service implementation:

@ Service public class StaffServiceImpl implements StaffService {@ Autowired StaffRepository staffRepository; / / can be injected directly into the Bean of our RersonRepository. @ Override / / uses the rollbackFor attribute of the @ Transactional annotation to specify that when a specific exception occurs, the data will be rolled back. @ Transactional (rollbackFor = {IllegalArgumentException.class}) public Staff saveStaffWithRollBack (Staff staff) {Staff s = staffRepository.save (staff); if (staff.getName (). Equals ("Zhang San") {throw new IllegalArgumentException ("Zhang San already exists, rollback");} return s;} @ Override public Staff saveStaffWithoutRollBack (Staff staff) {Staff s = staffRepository.save (staff) If (staff.getName (). Equals ("Zhang San") {throw new IllegalArgumentException ("Zhang San already exists, data will not be rolled back");} return s;}}

7.Controller:

@ RestController @ RequestMapping ("/ staff") public class StaffController {@ Autowired StaffService staffService; / / Test rollback @ RequestMapping ("/ rollback") public Staff rollback (Staff staff) {return staffService.saveStaffWithRollBack (staff);} / / Test does not roll back @ RequestMapping ("/ notrollback") public Staff noRollBack (Staff staff) {return staffService.saveStaffWithoutRollBack (staff);}}

8. Run the test:

(1) rollback: http://localhost:5000/staff/rollback?name= Zhang San & age=18

Console:

Database:

(2) No rollback: http://localhost:5000/staff/notrollback?name= Zhang San & age=18

Console:

Database:

The above is the content of this article on "what is the SpringBoot transaction mechanism". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report