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