SpringBoot&MyBatis添加事务

x33g5p2x  于2021-03-14 发布在 Spring  
字(1.1k)|赞(0)|评价(0)|浏览(366)

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();
    }
}

相关文章

微信公众号

最新文章

更多