SpringBoot事务以及通用mapper

springboot添加事务支持:

spring的事务管理分为两种方式;

  (1)编程式事务管理 :通过编写代码来实现事务管理         

  (2)声明式事务管理:通过aop技术来实现,开发中多采用基于注解的方式来做。

SpringBoot中通过注解来控制事务,只需要添加两个注解就可以了。事实上我们引入jdbc或者web的启动器,就已经引入事务相关的依赖及默认配置了 。

(1)在service层需要使用事务的方法上面添加注解:@Transactional

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User queryById(Long id){
        return this.userMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public void deleteById(Long id){
        this.userMapper.deleteByPrimaryKey(id);
    }
}

(2)在spring boot的引导类上添加开启事务管理的注解:@EnableTransactionManagement

通用mapper的使用:

通用mapper的网址:https://mapperhelper.github.io/docs/

(1)pom.xml中导入依赖:

<!-- 通用mapper -->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>

(2)定义mapper的接口直接使用:

@Mapper
public interface UserMapper extends tk.mybatis.mapper.common.Mapper<User>{//防止和@Mapper冲突


}

(3)在主程序类上配置mapper扫描器

@SpringBootApplication
@MapperScan(basePackages = {"com.szhhome.springbootmybatis.mapper"})
public class SpringbootMybatisApplication {

   public static void main(String[] args) {
      SpringApplication.run(SpringbootMybatisApplication.class, args);
   }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值