配置數據源
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
接口:
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註解開啓了事物