您的位置:首页 > 编程语言 > Java开发

第六节:SpringBoot之事务管理@Transactional

2017-09-04 17:39 429 查看
代码如下

package com.xiaowen.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="tb_account")
public class Account {

@Id
@GeneratedValue
private Integer id;
@Column(length=50)
private String userName;
private float balance;
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 float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}

}

dao
package com.xiaowen.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.xiaowen.model.Account;
/**
* 账户Dao
* @author xiaowen
*/
public interface AccountDao extends JpaRepository<Account, Integer> {

}
service
package com.xiaowen.service;
/**
* 账户service接口
* @author xiaowen
*/
public interface AccountService {

public void transferAccounts(int fromUser,int toUser,float account);
}
service实现类
package com.xiaowen.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xiaowen.dao.AccountDao;
import com.xiaowen.model.Account;
import com.xiaowen.service.AccountService;
/**
* 帐号Service实现类
* @author xiaowen
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Resource
private AccountDao accountDao;
@Transactional//事务
public void transferAccounts(int fromUser, int toUser, float account) {
Account fromUserAccount=accountDao.getOne(fromUser);
fromUserAccount.setBalance(account);
accountDao.save(fromUserAccount);//扣钱

Account toUserAccount=accountDao.getOne(toUser);
toUserAccount.setBalance(toUserAccount.getBalance()+account);
int k=1/0;
accountDao.save(toUserAccount);//加钱
}

}
controller
package com.xiaowen.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaowen.service.AccountService;

@RestController
@RequestMapping("/account")
public class AccountController {

@Resource
private AccountService accountService;

@RequestMapping("/transfer")
public String transferAccounts(){
try{
accountService.transferAccounts(1, 2, 200);
return "ok";
}catch(Exception e){
return "no";
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: