Detach an entity from JPA/EJB3 persistence context

后端 未结 14 2107
面向向阳花
面向向阳花 2020-12-13 03:26

What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in

相关标签:
14条回答
  • 2020-12-13 04:01

    If you need to detach an object from the EntityManager and you are using Hibernate as your underlying ORM layer you can get access to the Hibernate Session object and use the Session.evict(Object) method that Mauricio Kanada mentioned above.

    public void detach(Object entity) {
        org.hibernate.Session session = (Session) entityManager.getDelegate();
        session.evict(entity);
    }
    

    Of course this would break if you switched to another ORM provider but I think this is preferably to trying to make a deep copy.

    0 讨论(0)
  • 2020-12-13 04:04

    I think there is a way to evict a single entity from EntityManager by calling this

    EntityManagerFactory emf;
    emf.getCache().evict(Entity);
    

    This will remove particular entity from cache.

    0 讨论(0)
  • 2020-12-13 04:07

    (may be too late to answer, but can be useful for others)

    I'm developing my first system with JPA right now. Unfortunately I'm faced with this problem when this system is almost complete.

    Simply put. Use Hibernate, or wait for JPA 2.0.

    In Hibernate, you can use 'session.evict(object)' to remove one object from session. In JPA 2.0, in draft right now, there is the 'EntityManager.detach(object)' method to detach one object from persistence context.

    0 讨论(0)
  • 2020-12-13 04:07

    In JPA 1.0 (tested using EclipseLink) you could retrieve the entity outside of a transaction. For example, with container managed transactions you could do:

    public MyEntity myMethod(long id) {
        final MyEntity myEntity = retrieve(id);
        // myEntity is detached here
    }
    
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public MyEntity retrieve(long id) {
        return entityManager.find(MyEntity.class, id);
    }
    
    0 讨论(0)
  • 2020-12-13 04:08

    this is quick and dirty, but you can also serialize and deserialize the object.

    0 讨论(0)
  • 2020-12-13 04:09

    If using EclipseLink you also have the options,

    Use the Query hint, eclipselink.maintain-cache"="false - all returned objects will be detached.

    Use the EclipseLink JpaEntityManager copy() API to copy the object to the desired depth.

    0 讨论(0)
提交回复
热议问题