首页 > 解决方案 > SpringBoot @RestController 不止一个 @Transactional 方法

问题描述

每个人!配置:1. Spring Boot:Web、JPA、H2

应用:

@SpringBootApplication
public class BankApplication {

public static void main(String[] args) {
    SpringApplication.run(BankApplication.class, args);
}

}

BankAccountDaoImpl:

@Repository
public class BankAccountDaoImpl implements BankAccountDao {

@Autowired
private EntityManagerFactory entityManagerFactory;

@Override
public void saveBankAccount(BankAccount bankAccount) {
    Session currentSession = entityManagerFactory.unwrap(SessionFactory.class).openSession();

    currentSession.save(bankAccount);
}

@Override
public BankAccount getBankAccount(int id) {
    Session currentSession = entityManagerFactory.unwrap(SessionFactory.class).openSession();

    BankAccount bankAccount = currentSession.get(BankAccount.class, id);

    return bankAccount;
}
}

ClientAccountDaoImp:

@Repository
public class ClientAccountDaoImp implements ClientAccountDao{

@Autowired
private EntityManagerFactory entityManagerFactory;

@Override
public void saveClientAccount(ClientAccount clientAccount) {
    Session currentSession = entityManagerFactory.unwrap(SessionFactory.class).openSession();

    currentSession.saveOrUpdate(clientAccount);
}

@Override
public ClientAccount getClientAccount(int id) {
    Session currentSession = entityManagerFactory.unwrap(SessionFactory.class).openSession();

    return currentSession.get(ClientAccount.class, id);
}

BankAccountServiceImpl 和 ClientAccountServiceImpl:aitowired BankAccountDaoImpl 和 ClientAccountDaoImp

所有方法都有@Transactional 注释:

@Override
@Transactional
public void saveClientAccount(ClientAccount clientAccount) {
    clientAccountDao.saveClientAccount(clientAccount);
}

@Override
@Transactional
public ClientAccount getClientAccount(int id) {
    return clientAccountDao.getClientAccount(id);
}

我有@RestController:

   @GetMapping("/buy/{accountId}/sum/{money}")
   public ClientAccount chargeAccount(@PathVariable int accountId, 
   @PathVariable int money) {

    BankAccount bankAccount = bankAccountService.getBankAccount(1);
    int mn = bankAccount.getAmount() - money;
    bankAccount.setAmount(mn);
    bankAccountService.saveBankAccount(bankAccount);
    ClientAccount clientAccount = clientAccountService.getClientAccount(accountId);
    clientAccount.setAmount(money);

    clientAccountService.saveClientAccount(clientAccount);

    return clientAccount;
}

在方法中 clientAccountService.saveClientAccount(clientAccount);我有一个例外:

org.hibernate.HibernateException:非法尝试将代理 [com.sustavov.bank.entity.Client#1] 与两个打开的会话相关联

如果在道课上,我会做getCurrentSession()除了openSession()。我有一个错误:

javax.persistence.TransactionRequiredException:没有正在进行的事务

标签: hibernatespring-bootexceptionspring-data-jpaspring-transactions

解决方案


推荐阅读