Hibernate UnknownEntityTypeException报错求助:无法找到实体持久化器
问题
运行基于Hibernate和PostgreSQL的项目时出现报错:
Exception in thread "main" org.hibernate.UnknownEntityTypeException: Unable to locate persister: org.example.entity.Employee
相关代码如下:
Employee实体类
package org.example.entity; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @Setter @Getter @AllArgsConstructor @NoArgsConstructor public class Employee { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id @Column(name = "id", nullable = false) private Integer id; @Basic @Column(name = "name", nullable = true, length = 10) private String name; @Basic @Column(name = "surname", nullable = true, length = 15) private String surname; @Basic @Column(name = "office_id", nullable = true) private Integer officeId; }
hibernate.cfg.xml配置文件
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:postgresql://localhost:5432/postgres</property> <property name="connection.driver_class">org.postgresql.Driver</property> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> <property name="connection.username">postgres</property> <property name="connection.password">vfr4vgy7</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.show_sql">true</property> <mapping class="org.example.entity.Employee"/> <!-- DB schema will be updated if needed --> <!-- <property name="hibernate.hbm2ddl.auto">update</property> --> </session-factory> </hibernate-configuration>
Main主类
package org.example; import org.example.entity.Employee; import org.hibernate.Session; public class Main { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Employee employee = new Employee(); employee.setName("New"); employee.setSurname("Hero"); employee.setOfficeId(1); employee.setId(12); session.beginTransaction(); session.save(employee); session.getTransaction().commit(); session.close(); HibernateUtil.close(); } }
HibernateUtil工具类
package org.example; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; /** * Created by Ариорх on 27.05.2017. */ public class HibernateUtil { private static SessionFactory sessionFactory = null; static { Configuration cfg = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(cfg.getProperties()); sessionFactory = cfg.buildSessionFactory(builder.build()); } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void close(){ getSessionFactory().close(); } }
使用环境:PostgreSQL数据库、IntelliJ IDEA Ultimate版本,疑问:该报错是否因HibernateUtil类导致,如何解决?
问题分析与解决方案
这个报错的核心是Hibernate无法找到Employee实体的持久化器,HibernateUtil的写法确实是主要原因之一,以下是具体分析和修复步骤:
1. HibernateUtil的错误修复
原HibernateUtil在构建SessionFactory时,没有将配置中的实体映射信息正确关联到StandardServiceRegistry,导致SessionFactory无法识别实体类。
修改后的HibernateUtil:
package org.example; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory = null; static { try { Configuration cfg = new Configuration().configure(); StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .applySettings(cfg.getProperties()) .build(); // 确保配置中的实体映射被加载到SessionFactory sessionFactory = cfg.buildSessionFactory(registry); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void close(){ getSessionFactory().close(); } }
或者采用Hibernate 5.2+推荐的更简洁写法:
package org.example; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class HibernateUtil { private static StandardServiceRegistry registry; private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { registry = new StandardServiceRegistryBuilder().configure().build(); Metadata metadata = new MetadataSources(registry).getMetadataBuilder().build(); sessionFactory = metadata.getSessionFactoryBuilder().build(); } catch (Exception e) { e.printStackTrace(); if (registry != null) { StandardServiceRegistryBuilder.destroy(registry); } } } return sessionFactory; } public static void close() { if (registry != null) { StandardServiceRegistryBuilder.destroy(registry); } } }
2. 其他可能的排查点
- 依赖版本匹配:实体类使用了
jakarta.persistence.*包,说明是Hibernate 6.x或Jakarta EE版本,确保项目依赖中Hibernate版本与JPA规范匹配,避免javax.persistence和jakarta.persistence包冲突。 - 实体扫描配置:若修改HibernateUtil后仍报错,可在hibernate.cfg.xml中添加自动扫描配置:
<property name="hibernate.archive.autodetection">class,hbm</property> - 映射路径验证:确认
<mapping class="org.example.entity.Employee"/>的类路径拼写完全正确,实体类确实位于org.example.entity包下。 - 编译输出检查:在IntelliJ IDEA中,确认实体类已正确编译到
target/classes目录,无编译错误。
内容的提问来源于stack exchange,提问作者tonan
相关产品推荐
相关产品推荐

