If you have used Hibernate with JPA and using annotation to declare your entity bean then you might have seen this confusing error called "org.hibernate.MappingException: Unknown entity". This error message is so misleading that you could easily lose anywhere between few minutes to few hours looking at wrong places. I was using Spring 3 and Hibernate 3.6 when I got this error,which occurs when addEntity() method was executed. I checked everything, from Spring configuration file applicationContext.xml, Hibernate config file, my Entity class and DAO class to see whether my Entity class is annotated or not, but I was still getting this error message. After some goggling I eventually find that, it was an incorrect import which was causing this error. Both hibernate and JPA has @Entity annotation and some how Eclipse was automatically importing org.hibernate.annotations.Entity instead of javax.persistence.Entity annotation. Once I fixed this import issue, everything went smooth. Unfortunately, this error is not easy to spot, the org.hibernate.annotations.Entity import seemed completely appropriate to many programmers. For a newbie Java or hibernate developer it’s really hard to understand which Entity annotation to use, shouldn't be in org.hibernate.annotations.Entity, but instead it's javax.persistence.Entity. By the way, if you are using auto-complete functionality of Eclipse IDE, then you can blame it them, alternatively you can configure your preferred import in Eclipse.
Error :
Exception in thread “main” org.hibernate.MappingException: Unknown entity: Person
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:580)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1365)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:562)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:550)
Version : Spring 3 and Hibernate 3.6
Cause : Incorrect import for @Entity annotation, My entity class was incorrectly annotated by org.hibernate.annotations.Entity annotation rather than javax.persistence.Entity, which comes with JPA.
Solution : Use javax.persistence.Entity to annotate your entity beans. Don't import org.hibernate.annotations.Entity

Tidak ada komentar:
Posting Komentar