hibernate - 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:没有正在进行的事务
解决方案
推荐阅读
- javascript - 以编程方式在 Google Colab 中运行所有单元格命令
- jkube - jkube 资源失败:未知类型 CRD
- javascript - 匿名函数和在 React 组件中直接调用函数的区别
- html - HTML如何在新行上显示列表中的元素
- python - 通过来自另一个字典的嵌套 id 过滤字典列表
- php - Wordpress Loop - 不返回特定类别的项目
- capistrano - 使用 Capistrano 设置全新的 Rails 应用程序部署。删除了我的部署目录并重新部署,现在日志不起作用
- java - 查找n个数组树中具有相同名称的节点的所有子节点和子节点
- c# - 绑定到 actualWidth 不起作用,尽管它在设计器中起作用;wpf
- html - 嵌套的弹性列可防止子级限制到最大高度