简体   繁体   English

JPA Container管理的事务-如何在同一事务中更新多个实体

[英]JPA Container managed transactions - how to update multiple entities in the same transaction

I'm still new to JPA and how the entity manager works. 我对JPA以及实体管理器的工作原理仍然是陌生的。 I have an application configured with container managed transactions, and I'm trying to figure out how to persist multiple objects in a single transaction. 我有一个配置有容器管理的事务的应用程序,并且我试图弄清楚如何在单个事务中保留多个对象。 Here is what I tried first: 这是我首先尝试的方法:

@Stateless
public class UserManager{
 @PersistenceContext(unitname="dataPortal")
 EntityManager em;

 public void insertUser(User user)
 {
  em.getTransaction().begin();
  ChangeEvent event = new ChangeEvent("user created");
  em.persist(u);
  em.persist(event);
  em.getTransaction().commit();
 }

}

This throws an illegal state exception when I try to get the transaction. 当我尝试获取事务时,这将引发非法状态异常。 I found out through reading that you aren't suppose to touch the transaction when it is container managed. 通过阅读,我发现您不应该在容器管理的情况下接触事务。

What I want to do is make sure that the User and ChangeEvent objects are persisted in the same transaction. 我要做的是确保User和ChangeEvent对象在同一事务中保留。 How can I enforce that with container managed transactions? 如何使用容器管理的交易来强制执行?

Like you already said, the transactions are managed by the container. 就像您已经说过的,事务由容器管理。

If you want that both User and ChangeEvent are persisted in the same transaction just annotate your method the following way: 如果您希望UserChangeEvent都保留在同一个事务中,请使用以下方式注释您的方法:

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@TransactionManagement(TransactionManagementType.CONTAINER) 
public void insertUser(User user)
     {
      ChangeEvent event = new ChangeEvent("user created");
      em.persist(u);
      em.persist(event);
     }

This should do the trick. 这应该可以解决问题。 If you have further questions, feel free to ask. 如果您还有其他问题,请随时提问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM