Home >Database >Mysql Tutorial >Why Does Hibernate 5.0 Throw 'Unknown Entity' MappingException, and How Can I Fix It?
Hibernate MappingException: Unknown Entity in Hibernate 5
When integrating Hibernate 5.0 with MySQL, you may encounter the error "org.hibernate.MappingException: Unknown entity." This issue is prevalent in versions 5.0.0 and 5.0.1, but not in Hibernate 4.3.9.
Diagnosis
The issue stems from a mismatch in the Hibernate 5 configuration code. The following code fragment from your "HibernateMain.java" class is problematic:
Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); SessionFactory sf = configuration.buildSessionFactory(sr);
In Hibernate 5, using configuration.buildSessionFactory(sr) leads to a loss of mapping information acquired during configuration.configure().
Solution
To resolve this issue, employ the following approach without ServiceRegistry:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Additional Loading Options for Properties
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(). configure().loadProperties("hibernate-h2.properties").build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
File propertiesPath = new File("some_path"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(). configure().loadProperties(propertiesPath).build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
Conclusion
Avoid using the incorrect configuration method presented in the Hibernate 5 tutorial 1.1.6. Utilize the aforementioned solutions to rectify the "Unknown entity" issue and establish a successful Hibernate 5 integration with MySQL.
The above is the detailed content of Why Does Hibernate 5.0 Throw 'Unknown Entity' MappingException, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!