Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

JPA/Hibernate remove entity sometimes not working

I have the following code that usually works well:

public void delete(T object)
{
  EntityManager em = getPersistence().createEntityManager();
  EntityTransaction et = em.getTransaction();
  try
  {
    et.begin();
    object = em.find(object.getClass(), object.getId());
    em.remove(object);
    em.flush();
    et.commit();
  }
  catch(Exception e)
  {
    error("Unable to delete " + object.toString() + ": there are references to it.");
  }
  finally
  {
    if (et.isActive()) et.rollback();
    em.close();
  }
}

For many of my entity classes this just works. However for two of them it does nothing, it does not throw any exceptions and it does not delete the object. The log from hibernate shows that hibernate executes a number of select queries but it doesn't even try to execute a delete.

I've already tried suggestions found in other similar questions here and here, but to no avail (well, the latter suggests @Transactional which I can't use, but I just enclosed the statements between begin() and commit() instead).

I can't seem to find what those two classes have more (or less) than the others. They use @PrimaryKeyJoinColumn just like almost all other entities I have, they have @OneToMany and @ManyToOne just like ohters. To be honest, they do have a @OneToOne(optional = false) field that references another class and that other entities do not have, but I wouldn't go through the hassle of changing that (and consequently changing the database schema) unless you tell me there could be a reason for it.

Is @OneToOne responsible? Or is my delete code bugged?

question from:https://stackoverflow.com/questions/16898085/jpa-hibernate-remove-entity-sometimes-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...