首页 > 其他分享 >如何在Spring Boot开启事务

如何在Spring Boot开启事务

时间:2022-10-31 12:46:51浏览次数:39  
标签:事务 Spring Transactional Boot 开启 springframework org import public

说到事务,那什么是事务呢?

 

事务(Transaction),一般是指要做的或所做的事情。

  • 原子性(Atomicity):事务作为一个整体被执行,包含在其中的对数据库的操作要么全部被执行,要么都不执行。
  • 一致性(Consistency):事务应确保数据库的状态从一个一致状态转变为另一个一致状态。一致状态的含义是数据库中的数据应满足完整性约束。
  • 隔离性(Isolation):多个事务并发执行时,一个事务的执行不应影响其他事务的执行。
  • 持久性(Durability):已被提交的事务对数据库的修改应该永久保存在数据库中。

 

那么如何在Spring Boot中使用呢?其实只需要两步即可:

  1. 在Application上添加@EnableTransactionManagement注解,用来开启事务。
  2. 在Service实现类的方法上添加@Transactional注解。

具体实现:
使用《Spring Boot中使用MyBatis详解》的代码,在TransactionalApplication启动类上添加@EnableTransactionManagement注解开启事务:
package com.zxw.transactional;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
//开启事务
@EnableTransactionManagement
public class TransactionalApplication {

    public static void main(String[] args) {
        SpringApplication.run(TransactionalApplication.class, args);
    }

}
  在Service实现方法上添加@Transactional注解:  
package com.example.demo.gs;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.demo.DeptMapper;
import com.example.demo.DeptService;

@Service
public class DeptServiceImplement implements DeptService {
    @Autowired
    private DeptMapper Mapper;
    
    @Transactional
    @Override
    public List<Dept> selectFromService() {
        // TODO Auto-generated method stub
        return this.Mapper.select();
    }
    
    @Transactional
    @Override
    public Dept Insert(int id, String name, String location) {
        // TODO Auto-generated method stub
        return this.Mapper.insert(id, name, location);
    }

    @Transactional
    @Override
    public List<Dept> selectFromId(int id) {
        // TODO Auto-generated method stub
        return this.Mapper.selectFrom(id);
    }

    @Transactional
    @Override
    public void updateFromLocation(String location) {
        this.Mapper.updateFromLocation(location);
        
    }

    @Transactional
    @Override
    public List<Dept> Delete() {
        // TODO Auto-generated method stub
        return this.Mapper.deleteFromDept();
    }
    
}

 



标签:事务,Spring,Transactional,Boot,开启,springframework,org,import,public
From: https://www.cnblogs.com/ZhuAo/p/16843892.html

相关文章