JPA/Hibernate remove entity sometimes not working

拟墨画扇 提交于 2019-11-26 21:54:32
Steve Ebersole

Do you have associations in this graph that cascade a persist back to the thing being deleted? If so, the JPA spec states clearly that the provider is to cancel the delete in such a case. If this is the case, Hibernate writes out a log statement saying "un-scheduling entity deletion [...]". You could see that by enabling trace logging on the org.hibernate.event.internal.DefaultPersistEventListener logger.

If this is the situation, you'll need to clean up those associations as required by JPA specification.

Arthur Nederlof

Replacing the cascade = CascadeType.ALL by orphanRemoval = true in the @OneToMany association gives the expected result: The child records are correctly removed without the need to delete the parent record.

Pity that error is not logged more clearly.

I got the same issue when following things gathered together.

  1. Hibernate 3.6.10.Final
  2. Parent entity with no reference to Child.
  3. Some Child entity with reference to the Parent. It is legacy code.

    class ChildEntity {
      @ManyToOne(cascade = CascadeType.ALL)
      private ParentEntity parent;
    }
    
  4. Child entity is loaded into session context and then is removed from table without JPA notification within transaction (stored procedure, native sql)

  5. Then parent can't be deleted. No deletion, no exception, just 'un-schedule deletion' message in TRACE log.

Solution: I removed cascade attribute. It was a little bit difficult for me to find which Child entity blocks Parent deletion. Also, I do not understand why Child cascade affects if I remove Parent entity.

Besides all this, once you already have Cascade and Orphan correct, in my case I found another reason why the DELETE could not be made even when all looks fine and even when the DELETE are in the log but the database don't show any change.

It also could be a transactional issue, but, in my case it was that the Key (in Oracle Database) within the delete query was a CHAR(8) data type in the Database, in that case as you can find in the Oracle documentation CHAR versus VARCHAR2 if your data is not 8 length, the rest is cover with blank, and a JPA DELETE make distinction between "0001" and "0001 ".

I write this response due I don't see something like this in all my research and someone else could get through this post and have the same problem.

Cheers.

I had the same problem with an entity that has many relations. What I did was to set to null the parent entities, to do a merge, then make a flush and clear and finally, get the entity again using find and remove. For example:

objAgreement.setParent(null);
em.merge(objAgreement);
em.flush();
em.clear();

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