spring boot事物配置一(业务层)

1、需要的注解为@EnableTransactionManagement 和@Transactional 两个,它们来自于下边这个包:

	<dependency>
	    <groupId>org.mybatis.spring.boot</groupId>
	    <artifactId>mybatis-spring-boot-starter</artifactId>
	    <version>1.3.1</version>
	</dependency>

2.首先,找到你的service实现类,加上@Transactional 注解,如果你加在类上,那该类所有的方法都会被事务管理,如果你加在方法上,那仅仅该方法符合具体的事务。当然我们一般都是加在方法上。因为只有增、删、改才会需要事务。 

package com.mingde.services.impl;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
 
import com.mingde.dao.StudentDao;
import com.mingde.po.Student;
import com.mingde.services.StudentService;
 
 
@Service
public class StudentServiceImpl implements StudentService {
 
	@Autowired
	private StudentDao studentDao;
	
	@Override
	//@Transactional  只这样写默认是只读,下面的写法是用于增删改
	@Transactional(propagation=Propagation.REQUIRED)	//必须事务,错误时事务回滚
	public List<Student> findAll() throws Exception {
		return (List<Student>) studentDao.findAll();
	}
	
	
}

3.配置完后,spring boot启动类必须要开启事务,而开启事务用的注解就是@EnableTransactionManagement ,如下:

@SpringBootApplication
@EnableTransactionManagement 
@MapperScan("microservice.qssj.mapper")//必须加这个,不加报错,如果不加,也可以在每个mapper上添加@Mapper注释,并且这里还要多填一个注释,那个我忘了,我一直用这个注解
public class QssjServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(QssjServiceApplication.class, args);
    }
}

这样就完成了事务的配置。

注意:

1.默认遇到throw new RuntimeException(“…”);会回滚 
   需要捕获的throw new Exception(“…”);不会回滚

2.如果有事务,那么加入事务,没有的话新建一个(不写的情况下)

@Transactional(propagation=Propagation.REQUIRED) 
容器不为这个方法开启事务

@Transactional(propagation=Propagation.NOT_SUPPORTED)
readOnly=true只读,不能更新,删除

@Transactional (propagation = Propagation.REQUIRED,readOnly=true) 
设置超时时间

@Transactional (propagation = Propagation.REQUIRED,timeout=30)
设置数据库隔离级别

@Transactional (propagation = Propagation.REQUIRED,isolation=Isolation.DEFAULT)
 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值