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);
}
}