简体   繁体   中英

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 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.
  2. Note that merge() returns a merged entity that may be not the same as an entity passed in.

See also:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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