Detach an entity from JPA/EJB3 persistence context

后端 未结 14 2137
面向向阳花
面向向阳花 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.

提交回复
热议问题