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

}
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot可以很方便地整合通用Mapper,只需要在pom.xml中添加通用Mapper的依赖,然后在配置文件中配置数据源和通用Mapper的相关属性即可。 具体步骤如下: 1. 在pom.xml中添加通用Mapper的依赖: ```xml <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> ``` 2. 在配置文件中配置数据源和通用Mapper的相关属性: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml configuration: map-underscore-to-camel-case: true mapper: mappers: - tk.mybatis.mapper.common.Mapper not-empty: false identity: MYSQL ``` 其中,mapper.mappers指定了要使用Mapper接口,这里使用通用MapperMapper接口;mapper.identity指定了主键生成策略,这里使用了MySQL的自增长主键。 3. 在Mapper接口中继承通用MapperMapper接口即可使用通用Mapper提供的方法: ```java public interface UserMapper extends Mapper<User> { } ``` 这样就可以使用通用Mapper提供的方法来进行数据库操作了,例如: ```java @Autowired private UserMapper userMapper; public void addUser(User user) { userMapper.insert(user); } public void updateUser(User user) { userMapper.updateByPrimaryKeySelective(user); } public void deleteUser(Long id) { userMapper.deleteByPrimaryKey(id); } public User getUser(Long id) { return userMapper.selectByPrimaryKey(id); } public List<User> getUsers() { return userMapper.selectAll(); } ``` 以上就是Spring Boot整合通用Mapper的基本步骤,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值