我是 Java(和 Hibernate)新手,为了学习 Java,我想使用数据库创建具有简单 CRUD 操作的普通 Java 应用程序。我找到了有关设置休眠的文章,因此我按照它进行操作,结果如下:
import jakarta.persistence.*;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name")
private String firstname;
@Column(name = "lastname")
private String lastname;
// constructor
// getters and setters
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/db_student</property>
<property name="hibernate.connection.username">my username</property>
<property name="hibernate.connection.password">my password</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.model.Student"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory sessionJavaConfigFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory buildSessionJavaConfigFactory() {
try {
Configuration configuration = new Configuration();
//Create Properties, can be read from property files too
Properties props = new Properties();
props.put("hibernate.connection.driver_class", "org.postgresql.Driver");
props.put("hibernate.connection.url", "jdbc:postgresql://localhost:5432/db_student");
props.put("hibernate.connection.username", "my username");
props.put("hibernate.connection.password", "my password");
props.put("hibernate.current_session_context_class", "thread");
configuration.setProperties(props);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
public static SessionFactory getSessionJavaConfigFactory() {
if(sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory();
return sessionJavaConfigFactory;
}
}
在 Main.java 中我放入:
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Student fetchedStudent = session.get(Student.class, 1);
if (fetchedStudent != null) {
System.out.println("Student found: " + fetchedStudent.getFirstname());
} else {
System.out.println("Student not found.");
}
transaction.commit();
session.close();
}
}
但我不断收到错误:
线程“main”中的异常org.hibernate.UnknownEntityTypeException:无法找到实体描述符:com.model.Student
我发现问题可能出在使用较旧的 hibernate 版本,但就我而言,在我的 pom.xml 中我有:
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.6.1.Final</version>
</dependency>
这是因为 Hibernate 不知道您的
Student
实体。
自 Hibernate 5 起,
Configuration.configure()
方法已被破坏。如果您想通过 hibernate.cfg.xml
添加映射,请使用 MetadataSources:
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
或者您可以简单地使用
Configuration.addAnnotatedClass()
注册您的实体
configuration.addAnnotatedClass(Student.class);