天天看点

Day45SpringBoot2.0完成业务集成事务管理

src\main\java\com\dev1\service\IAccountService.java

package com.dev1.service;

import com.dev1.entity.Account;

import java.util.List;

public interface IAccountService {
    public void addAccount(Account account);
    public void updateAccount(Account account);
    public void deleteAccountById(String id);
    public Account findAccountById(String id);
    public List<Account> findAccounts();
    public void transfer(String fromId,String toId,Double money);
}      
package com.dev1.service.impl;

import com.dev1.entity.Account;
import com.dev1.mapper.Account1Dao;
import com.dev1.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional(readOnly = false,isolation = Isolation.READ_COMMITTED,propagation= Propagation.REQUIRED)
public class AccountServiceImpl implements IAccountService {
    @Autowired
    Account1Dao dao;
    @Override
    public void addAccount(Account account) {
        dao.add(account);
    }

    @Override
    public void updateAccount(Account account) {
        dao.update(account);
    }

    @Override
    public void deleteAccountById(String id) {
        dao.delete(id);
    }

    @Override
    public Account findAccountById(String id) {
        return dao.findById(id);
    }

    @Override
    public List<Account> findAccounts() {
        return dao.findAll();
    }

    @Override
    public void transfer(String fromId, String toId, Double money) {
        //拿到账号,查询户主,余额
        Account from = dao.findById(fromId);
        Account to = dao.findById(toId);
        //判断余额是否足够
        if(from.getValue() >= money){
            from.setValue(from.getValue()-money);
            to.setValue(to.getValue()+money);
            //同步到数据库
            dao.update(from);
            //System.out.println(1/0);//系统报错
            dao.update(to);
        }else{
            throw  new RuntimeException("余额不足...搬砖");
        }
    }
}      
package com.dev1.service.impl;

import com.dev1.service.IAccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class AccountServiceImplTest {

    @Autowired
    IAccountService accountService;
    @Test
    void transfer1() {
        accountService.transfer("1000","1002",10000D);
    }
    @Test
    void transfer2() {
        accountService.transfer("1000","1002",1D);
    }
}