Hibernate 5: MappingException: Unknown Entity
In Hibernate 5, the org.hibernate.MappingException: Unknown entity error can occur when attempting to integrate with MySQL. This issue is specific to versions 5.0.0 and 5.0.1 of Hibernate and is resolved in subsequent versions.
原因
The error stems from a change in Hibernate 5's behavior. In earlier versions, configuration information was retained within Configuration even after building the ServiceRegistry. However, in Hibernate 5, the Configuration loses this information when configuration.buildSessionFactory(sr) is called.
修复
1. Standard Configuration Files:
If using standard hibernate.cfg.xml and hibernate.properties files, create the session factory directly:
<code class="java">SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();</code>
2. Loading Properties:
If properties are stored in a different file, use StandardServiceRegistryBuilder:
Loading Properties as a Resource:
<code class="java">ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .configure() .loadProperties("hibernate-h2.properties") .build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry); </code>
Loading Properties from a File Path:
<code class="java">File propertiesPath = new File("some_path"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .configure() .loadProperties(propertiesPath) .build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);</code>
3. Using Fluent Hibernate Utility:
For a complete example using this approach, refer to the fluent-hibernate-mysql project on GitHub.
4. Avoiding Incorrect Hibernate 5 Tutorial Recommendations:
The erroneous code snippet provided in the Hibernate 5 tutorial:
<code class="java">return new Configuration().configure().buildSessionFactory( new StandardServiceRegistryBuilder().build() );</code>
does not perform proper configuration and should be avoided.
The above is the detailed content of How to Fix 'MappingException: Unknown Entity' in Hibernate 5 when Integrating with MySQL?. For more information, please follow other related articles on the PHP Chinese website!