java - Hibernate 和 EJB:如何正确使用 @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)?
问题描述
我有以下代码,我希望在方法中保留全部或不entities
保留。
然而,有些entities
是被创建的,而另一些不是 - 即整体transaction
没有被回滚。
为什么会这样?
注意 - 我正在将我的代码作为服务器中的EAR
文件运行JBOSS EAP
@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
public void createCompanyStatuses(String client, CompanyStatusPostDTO companyStatusPostDTO) {
EntityManager entityManager = null;
try {
CompanyStatus companyStatus = new CompanyStatus();
companyStatus.setCompanyLabel(candidateMaskedStatusPostDTO.getCompanyLabel());
entityManager = entityManagement.createEntityManager(client);
entityManager.persist(companyStatus);
for(Integer employeeStatusId: companyStatusPostDTO.getEmployeeStatuses()){
CompanyStatusEmployeeStatus companyStatusEmployeeStatus = new CompanyStatusEmployeeStatus();
companyStatusEmployeeStatus.setEmployeeId(employeeStatusId);
companyStatusEmployeeStatus.setCompanyId(companyStatus.getCompanyId()); //todo - how will get this?
entityManager.persist(CompanyStatusEmployeeStatus);
}
} catch(Exception e){
log.error("An exception has occurred in inserting data into the table" + e.getMessage(), e);
} finally {
entityManagement.closeEntityManager(client, entityManager);
}
}
解决方案
答案对 有效Hibernate
。
TransactionAttributeType.REQUIRES_NEW
不支持。
很难在 java 对象上实现回滚。想象一下场景:
- 交易开始
- 创建并保存对象
- 子事务开始
- 对象已修改
- 子事务回滚。
您希望对象处于子事务开始之前的状态,因此您需要跟踪有关在子事务中修改该对象的信息以及回滚这些修改的能力。
或者,您可以从 DB 重新加载状态,但您需要跟踪哪个对象属于哪个事务。
我假设开发人员只是认为这是太多的努力而收效甚微。
推荐阅读
- resilience4j - 将 Prometheus 指标与 CircuitBreakerConfigCustomizer 一起使用
- jmeter - 如何管理客户端证书的大型密钥库以使用 JMeter 加载测试 Mutual TLS
- python - 用python中的字符串替换列表中的多个字符串并获取替换字符串出现的计数
- javascript - Android反应原生接近传感器
- python - sqlalchemy 连接烧瓶
- javascript - 获取请求后重定向需要两次点击?
- objective-c - TVOS 上的 contentOverlayView 未显示
- assembly - 如何在 x86 程序集中将 16 位寄存器移动到 8 位寄存器?
- regex - Delphi中用于StringList中所有匹配行的正则表达式
- c++ - 我是否正确推理缓存性能?