在 Spring Boot 中启用事务管理器,需要执行以下步骤:
- 在 pom.xml 文件中添加事务管理器依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
- 在 application.properties 文件中配置数据源和事务管理器:
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 事务管理器配置
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=5
spring.datasource.tomcat.default-auto-commit=false
spring.datasource.tomcat.initial-size=5
# 开启事务支持
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.transaction.coordinator_class=org.hibernate.transaction.JDBCTransactionFactory
spring.jpa.properties.hibernate.transaction.flush_before_completion=true
spring.jpa.properties.hibernate.transaction.auto_close_session=true
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
- 在需要开启事务的方法上添加 @Transactional 注解:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Transactional
@Override
public void save(User user) {
userRepository.save(user);
}
}
注:@Transactional 注解可以放在类级别或方法级别,放在类级别表示该类所有方法都开启事务支持。如果需要控制事务的传播行为、隔离级别、超时时间等,可以通过@Transactional 注解的属性进行配置。