springboot開啟事務很簡單,只需要一個註解@Transactional 就可以了。因為在springboot中已經預設對jpa、jdbc、mybatis開啟了事事務,引入它們依賴的時候,事物就預設開啟。當然,如果你需要用其他的orm,比如beatlsql,就需要自己配置相關的事物管理器。
準備階段
以上一篇文章的程式碼為例子,即springboot整合mybatis,上一篇文章是基於註解來實現mybatis的資料訪問層,這篇文章基於xml的來實現,並開啟宣告式事務。
環境依賴
在pom檔案中引入mybatis啟動依賴:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
引入mysql 依賴:
<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>
初始化資料庫指令碼
-- create table `account`
# 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
mybatis.type-aliases-package=com.forezp.entity
通過配置mybatis.mapper-locations來指明mapper的xml檔案存放位置,我是放在resources/mybatis檔案下的。mybatis.type-aliases-package來指明和資料庫對映的實體的所在包。
經過以上步驟,springboot就可以通過mybatis訪問資料庫來。
建立實體類
public class Account {
private int id ;
private String name ;
private double money;
getter..
setter..
}
資料訪問dao 層
介面:
public interface AccountMapper2 {
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.AccountMapper2">
<update id="update">
UPDATE account set money=#{money} WHERE id=#{id}
</update>
</mapper>
service層
@Service
public class AccountService2 {
@Autowired
AccountMapper2 accountMapper2;
@Transactional
public void transfer() throws RuntimeException{
accountMapper2.update(90,1);//使用者1減10塊 使用者2加10塊
int i=1/0;
accountMapper2.update(110,2);
}
}
@Transactional,宣告事務,並設計一個轉賬方法,使用者1減10塊,使用者2加10塊。在使用者1減10 ,之後,丟擲異常,即使用者2加10塊錢不能執行,當加註解@Transactional之後,兩個人的錢都沒有增減。當不加@Transactional,使用者1減了10,使用者2沒有增加,即沒有操作使用者2 的資料。可見@Transactional註解開啟了事物。
結語
springboot 開啟事物很簡單,只需要加一行註解就可以了,前提你用的是jdbctemplate, jpa, mybatis,這種常見的orm。
原始碼下載:https://github.com/forezp/Spr…