新建SpringBoot项目SpringDataTransaction
新建个数据库db_bank 模拟银行转账,张三账户给李四转账,那么张三账户金额要减少,李四账户金额要增加,且张三减少的金额等于李四增加的金额
1.新建个Account.java账户实体
package com.guo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity // 实体 @Table(name="t_count") // 表 public class Account { @Id // 组件 @GeneratedValue //表 自增 private Integer id; // 主键 @Column(length=50) // 对应字符串 长度100(自定义) private String userName; //用户名 private Integer count; // 存款金额 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } }
2.新建AccountDao 接口
package com.guo.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.guo.entity.Account; public interface AccountDao extends JpaRepository<Account,Integer>{ }
3.这把多了个service接口
package com.guo.service; public interface AccountService { //声明个客户转账的方法 public void tranMoney(int fromUser,int toUser,int count); }
4.service接口实现类
package com.guo.service.impl; import javax.annotation.Resource; import javax.transaction.Transactional; import org.springframework.stereotype.Service; import com.guo.dao.AccountDao; import com.guo.entity.Account; import com.guo.service.AccountService; @Service("AccountService") public class AccountServiceImpl implements AccountService{ @Resource private AccountDao accountDao; @Transactional public void tranMoney(int fromUser, int toUser, int count) { Account fromAccount=accountDao.getOne(fromUser); fromAccount.setCount(fromAccount.getCount()-count); accountDao.save(fromAccount); Account toAccount=accountDao.getOne(toUser); toAccount.setCount(toAccount.getCount()+count); int zero=1/0; // 加的异常 accountDao.save(toAccount); } }
5.新建个AccountController
package com.guo.service.impl; import javax.annotation.Resource; import javax.transaction.Transactional; import org.springframework.stereotype.Service; import com.guo.dao.AccountDao; import com.guo.entity.Account; import com.guo.service.AccountService; @Service("AccountService") public class AccountServiceImpl implements AccountService{ @Resource private AccountDao accountDao; @Transactional public void tranMoney(int fromUser, int toUser, int count) { Account fromAccount=accountDao.getOne(fromUser); fromAccount.setCount(fromAccount.getCount()-count); accountDao.save(fromAccount); Account toAccount=accountDao.getOne(toUser); toAccount.setCount(toAccount.getCount()+count); //搞个异常int zero=1/0; accountDao.save(toAccount); } }
6.测试
刚开始张三和李四 账户各有500
如果加个异常int zero=1/0;
Service.impl不加 @Transactional标签时 会报异常
运行结果为NO,此时张三账户少了200,但是李四账户并没多200
加个@Transactional,运行虽结果虽为NO 但是张三少200,同时李四多200,体现了事务的一致性