When integrating Hibernate 5.0 with MySQL, developers may encounter the error message "org.hibernate.MappingException: Unknown entity." This issue arises in Hibernate 5.0.0 and 5.0.1 but not in Hibernate 4.3.9.
To resolve this error, it's essential to understand why it occurs. In Hibernate 5, unlike previous versions, the default configuration process does not automatically load entity mappings. This means that when configuration.buildSessionFactory(sr) is called, it lacks information about mapped entities.
Incorrect Hibernate 5 Tutorial:
The Hibernate 5 tutorial provides an incorrect code sample that leads to this error:
return new Configuration().configure().buildSessionFactory( new StandardServiceRegistryBuilder().build() );
This code doesn't properly configure the entity mappings.
To fix the issue, you can load entity mappings correctly using one of the following methods:
Standard Configuration Files: Use the simplified approach if you have standard configuration files hibernate.cfg.xml and hibernate.properties:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Load Properties: For other property files, use a StandardServiceRegistryBuilder to load properties:
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .configure().loadProperties("hibernate-h2.properties").build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
This requires the hibernate-h2.properties file to be in the classpath.
Load Properties from Path: Use this method to load properties from a specific file path:
File propertiesPath = new File("some_path"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .configure().loadProperties(propertiesPath).build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
By using one of these solutions to load entity mappings, you can resolve the "Unknown Entity" error when integrating Hibernate 5.0 with MySQL. Remember that the incorrect code sample in the Hibernate 5 tutorial should be avoided.
The above is the detailed content of Why am I Getting \'org.hibernate.MappingException: Unknown Entity\' in Hibernate 5 with MySQL?. For more information, please follow other related articles on the PHP Chinese website!