开发者

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

@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 vo开发者_Go百科id 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.
  2. Note that merge() returns a merged entity that may be not the same as an entity passed in.

See also:

  • what is the difference between persist() and merge() in hibernate..?


Per spec merge can be used as for persist purposes as for updating. The decision is making on presence of @Id value. So JPA itself provide most efficient way to store your entity


You don 't call EntityManagers functions in the entities. You would create a new X and add the Y's to it. Calling EntitiManager.persist() in the end.

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

Your entities should not know about JPA / Hibernate / Transactions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜