0
votes

I cannot make a simple create/delete to work, across transactions. I use Spring/JPA/Hibernate, no ehcache.

My entity class User, and MyDao with two methods marked by Spring's @Transactional (I understand @Transactional should be on service, here is just simplify my case)


    public class MyDao {
      @PersistenceContext
      private EntityManager entityManager;

      @Transactional
      public void create(User user) {
        entityManager.persist(user);
        entityManager.refresh(user);
      }

      @Transactional
      public void delete(User user) {
        // Since user maybe detached, I use Hibernate to delete.
        Session sess = entityManager.unwrap(Session.class);
        sess.delete(user);
      }
    }

My test:


    {
      User user = new User();
      myDao.create(user);

      // above is ok. user created with generated ID.
      // and I assume the transaction is closed, so user is detached

      myDao.delete(user);

      // above failed with error "Removing a detached instance ..."
    }

According to Hibernate, session.delete() can delete either detached or managed. But why it failed?

Thanks for help

Michael

1

1 Answers

0
votes

Hibernate document said you can operate on detached entity only when it overrides equals() and hashCode(). I'll see if it works when getting back to work tomorrow. Two things I'm not happy with:

  • If detached previously, the entity must have value for identity field, why don't just use it?
  • The document...

Our db tables have long and string for ID columns, so I cannot use a base entity class with an abstract getId(). I almost went on to implement a method to retrieve @Id field via reflection from our entity classes, then pure JPA to find() first then delete.

BTW, I'm talking about generic methods applied to all our entities, not just one User class.