Home >Database >Mysql Tutorial >How to Resolve 'org.hibernate.MappingException: Unknown Entity' in Hibernate 5?

How to Resolve 'org.hibernate.MappingException: Unknown Entity' in Hibernate 5?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 08:20:10552browse

How to Resolve

org.hibernate.MappingException: Unknown Entity in Hibernate 5

Problem: An exception occurs with the message "org.hibernate.MappingException: Unknown entity" when attempting to integrate Hibernate 5.0 with MySQL.

Cause: This issue is encountered specifically with Hibernate 5.0.0 and 5.0.1 versions but not with Hibernate 4.3.9. The error stems from a discrepancy in how Hibernate 5 handles configuration compared to previous versions.

Solution: To resolve this issue, adjust the code responsible for creating the SessionFactory:

// Incorrect approach for Hibernate 5
Configuration configuration = new Configuration();
configuration.configure();

ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

SessionFactory sf = configuration.buildSessionFactory(sr);

Correct approach for Hibernate 5:

  • Standard XML Configuration Files (hibernate.cfg.xml and hibernate.properties):
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  • Loading Properties from a non-standard file:
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().loadProperties("hibernate-h2.properties").build();
SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
  • Loading Properties from File Path:
File propertiesPath = new File("some_path");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().loadProperties(propertiesPath).build();
SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);

The above is the detailed content of How to Resolve 'org.hibernate.MappingException: Unknown Entity' in Hibernate 5?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn