Nikita
Nikita

Reputation: 6079

why does Hibernate's EntityManager.find() impl throw EntityNotFoundException?

JPA 2.0 javadoc (and probably the spec) say that EntityManager.find() returns null when entity isn't found:

the found entity instance or null if the entity does not exist

Yet Hibernate's impl throws EntityNotFoundException instead. Why? Observed using Hibernate 3.6.8 and hibernate-jpa-2.0-api v1.0.1.Final

javax.persistence.EntityNotFoundException: Unable to find bar.foo.Entity with id 144487 at org.hibernate.ejb.Ejb3Configuration$Ejb3EntityNotFoundDelegate.handleEntityNotFound(Ejb3Configuration.java:137) at org.hibernate.event.def.DefaultLoadEventListener.returnNarrowedProxy(DefaultLoadEventListener.java:320) at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:277) at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:1005) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:998) at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:779) at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:754)

Upvotes: 4

Views: 3148

Answers (1)

Federico
Federico

Reputation: 1731

I was having the same problem using Hibernate 4.1.x and wanted to provide a pointer to someone experiencing the same problem. In my case, as mentioned in previous comments, it wasn't the entity itself, but rather another entity referenced from the loaded entity. The strange thing was that this referenced entity did exist, but it was accessed in a different transaction/session and that made the difference. Since I was writing a test using spring the simple change of moving @transactional from the class level to a method broke the whole thing.

Upvotes: 4

Related Questions