SpringBoot中添加事务非常简单,只需将@Enable TransactionManagement标注在启动类上,将@Transactional标注在service层的实现类中需要添加事务的方法上即可。如下:com/example/sboot/SbootApplication.java
(启动类)
package com.example.sboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication // 标注该类为启动类
@MapperScan("com.example.sboot.dao") //找到dao层下的接口
@EnableTransactionManagement // 支持事务
public class SbootApplication {
public static void main(String[] args) {
SpringApplication.run(SbootApplication.class, args);
}
}
com/example/sboot/UserServiceImpl.java
package com.example.sboot.service;
import com.example.sboot.dao.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl implements UserService{
@Resource
private UserMapper userMapper = null;
@Override
@Transactional // 支持事务
public Integer queryUserCounts() {
return userMapper.queryUserCounts();
}
}
内容来源于网络,如有侵权,请联系作者删除!