javax.persistence.Entitymanager: remove() method

前端 未结 4 1919
梦毁少年i
梦毁少年i 2021-01-31 19:00

Does remove(Object entity) method of EntityManager work only on those objects got from find() method?

I have following code snippet:

4条回答
  •  情深已故
    2021-01-31 19:50

    Something to that direction. EntityManager.remove works only for managed entities. How you obtained these managed entities does not matter, it can be for example:

    • via JPQL query
    • via Criteria API query
    • find method in EntityManager
    • by following relationship from some other entity.
    • created new entity and persisted it

    But simply creating new object and trying to remove it does not work, because this new object is not managed entity. Also entity should not be yet detached.

    Life of entity is quite much as follows, all in same transaction (entities outside their transaction are not managed):

    Entity ent = new Entity(1); //entity is in new state, EntityManager never know
                                //anything about it
    em.persist(ent); //entity is managed as long as not disconnected 
                     //from EntityManager
    em.clear(); // all previously managed entities, including ent, are now detached
    
    Entity same = em.find(1); //managed same
    em.remove(same); // entity is removed
    

提交回复
热议问题