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)