简体   繁体   English

Hibernate JPA:如何编写有效的persist()?

[英]Hibernate JPA: how to write an efficent persist()?

The below code seem simple, yet it takes me long time but turned out to be cumbersome and lengthy code even i dislike. 下面的代码看起来很简单,但是花了我很长时间,但是即使我不喜欢它,也很麻烦而且冗长。 could someone help me with some efficient code? 有人可以帮助我提供一些有效的代码吗? many thanks. 非常感谢。 by the way, i'm using hibernate 3.6 JPA implementation 顺便说一句,我正在使用休眠3.6 JPA实现

@Entity
class X
{
     @OneToMany( fetch = FetchType.EAGER, mappedBy = "x", cascade = { CascadeType.PERSIST, CascadeType.MERGE } )
     private Set<Y> ys = new HashSet<Y>();

     public void persist()
     {
        //here, this(x) is newly create but its ys are already in the DB, so how to write the code?
     }

     public void merge()
     {
       //like persist(), the ys of this(x) is changed, how to merge effiently?
     }

} }

i use the below but it will throw exception: Cannot fetch unpersisted entity 我使用以下内容,但会引发异常:无法获取未持久化的实体

     public void merge()
     {
             EntityManager em = entityManager();
             EntityTransaction tx = em.getTransaction();
             try
             {
               tx.begin();
               for(Y y: ys)
                  em.merge(y);
               em.merge(this);
               tx.end();
             }
             finally
             {
                ...
             }
      }
  1. You can use merge() for persisting new entities. 您可以使用merge()持久化新实体。
  2. Note that merge() returns a merged entity that may be not the same as an entity passed in. 请注意, merge()返回的合并实体可能与传入的实体不同。

See also: 也可以看看:

Per spec merge can be used as for persist purposes as for updating. 每个规格合并可用于持久性目的,也可用于更新。 The decision is making on presence of @Id value. 决定是否存在@Id值。 So JPA itself provide most efficient way to store your entity 因此,JPA本身提供了最有效的方式来存储您的实体

You don 't call EntityManagers functions in the entities. 您不要在实体中调用EntityManagers函数。 You would create a new X and add the Y's to it. 您将创建一个新的X并将其添加到Y。 Calling EntitiManager.persist() in the end. 最后调用EntitiManager.persist()。

X x = new new X();
for(Y y : findSomeYsilons() ) {
   x.add(y);
}
em.persist(x);

Your entities should not know about JPA / Hibernate / Transactions. 您的实体不应该了解JPA / Hibernate /事务。

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

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