JPA EntityManager with Hibernate - find and remove does not delete data from database

穿精又带淫゛_ 提交于 2019-12-08 08:57:11

问题


Having trouble getting the following code to work...

I've got a JpaTransactionManager txManager autowired into this test. I know record with ID 39 does exist. It still exists at the end of the transactions, too...

    TransactionStatus status = txManager.getTransaction(def);
    A a = mock(A.class);
    when(a.getId()).thenReturn(Long.valueOf(39));
    sut.delete(a);
    txManager.commit(status);

    status = txManager.getTransaction(def);
    a = sut.get(a.getId());
    txManager.commit(status);

    assertNull(a);

Code in class A:

public void delete(A a) {

    a = getEntityManager().find(A.class, a.getId());
    getEntityManager().remove(a);

}

Is there any reason the above assertNull check always fails? I cannot delete the object from my system no matter what I do - no error returned, and no issue with the delete reported. (As an aside, running a query directly in HQL does result in an update of the database...I just can't get it to work using the delete method supplied using JPA...)

Any assistance appreciated


回答1:


You should take a look into these Hibernate classes/methods:

org/hibernate/engine/spi/ActionQueue.java executeActions(), unScheduleDeletion()
org/hibernate/event/internal/DefaultPersistEventListener.java onPersist()

I had the same problem - not being able to remove an entity. In my case, entityManager had two entities in its 'context': a parent with a list of children entities (cascade = CascadeType.ALL) and a child (from the list) to remove. So when I was trying to remove a child, parent still had a link to it, which was causing Hibernate to 'unScheduleDeletion' upon flushing.

So here is the solution:

  1. Add orphanRemoval = true to the collection of children
  2. Create method deleteChild(Child child) {child.setParent(null); children.remove(child);}
  3. Use this method to delete children

Looks like another solution is to remove cascading, so that merging of parent entity wouldn't cause saving all its children. Not quite sure here (haven't checked).

Also, as far as I remember, JPA spec describes this situation.



来源:https://stackoverflow.com/questions/19163262/jpa-entitymanager-with-hibernate-find-and-remove-does-not-delete-data-from-dat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!