spring boot开启事务只需要一个简单的注解@Transactional,它默认已经对jdbc、jpa、mybatis开启了事务,引入它们依赖的时候,事物就默认开启,如果是其它的orm框架如beetlsql,则需要自行配置事务管理器。
这里基于xml来实现spring boot对mybatis的访问。
第一步:pom引入mybatis依赖、mysql依赖和druid连接池依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
初始化SQL脚本
# DROP TABLE `account` IF EXISTS
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `account` VALUES ('1', 'aaa', '1000');
INSERT INTO `account` VALUES ('2', 'bbb', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');
配置数据源文件
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml //指明mapper的xml文件所在位置
mybatis.type-aliases-package=com.forezp.entity // 指明和数据库映射的实体所在包,用以设置别名
经过上述配置,springboot就可以通过mybatis访问数据库
// 创建entity类
@Data
public class Account {
private int id;
private String name;
private double money;
}
// 创建mapper接口类
public interface AccountMapper {
int update( @Param("money") double money, @Param("id") int id);
}
// mapper映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.forezp.dao.AccountMapper">
<update id="update">
UPDATE account set money=#{money} WHERE id=#{id}
</update>
</mapper>
// 创建service类
@Service
public class AccountService {
@Autowired
AccountMapper accountMapper;
@Transactional // 为方法添加事务
public void transfer() throws RuntimeException{
accountMapper.update(90,1);//用户1减10块 用户2加10块
int i = 1/0;
accountMapper.update(110,2);
}
}
总结:spring boot开启事务很简单,添加一行注解就可以解决,不过前提是jdbcTemplate、jpa、mybatis等常见的orm框架。
转载:https://www.toutiao.com/i6647689066294804995/
本文详细介绍了如何在SpringBoot项目中整合MyBatis框架,包括依赖引入、数据源配置、实体类创建、Mapper接口定义及XML映射文件编写,并通过一个转账的例子展示了事务的使用。
527

被折叠的 条评论
为什么被折叠?



