JPA EntityManager: Why use persist() over merge()?

后端 未结 15 1437
说谎
说谎 2020-11-22 03:09

EntityManager.merge() can insert new objects and update existing ones.

Why would one want to use persist() (which can only create new objec

15条回答
  •  广开言路
    2020-11-22 03:27

    I was getting lazyLoading exceptions on my entity because I was trying to access a lazy loaded collection that was in session.

    What I would do was in a separate request, retrieve the entity from session and then try to access a collection in my jsp page which was problematic.

    To alleviate this, I updated the same entity in my controller and passed it to my jsp, although I imagine when I re-saved in session that it will also be accessible though SessionScope and not throw a LazyLoadingException, a modification of example 2:

    The following has worked for me:

    // scenario 2 MY WAY
    // tran starts
    e = new MyEntity();
    e = em.merge(e); // re-assign to the same entity "e"
    
    //access e from jsp and it will work dandy!!
    

提交回复
热议问题