user2482461
user2482461

Reputation: 236

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

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

Upvotes: 2

Views: 6348

Answers (1)

Ivan
Ivan

Reputation: 847

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.

Upvotes: 5

Related Questions