Я новичок в Java (и Hibernate), и для изучения Java я хочу создать простое Java-приложение с простыми операциями CRUD с использованием базы данных. Я нашел статью о настройке спящего режима, поэтому проследил за ней, и результат ниже:
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
org.postgresql.Driver
jdbc:postgresql://localhost:5432/db_student
my username
my password
1
thread
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< /p>
Я обнаружил, что проблема может быть связана с использованием более старой версии спящего режима, но в моем случае в моем pom.xml у меня есть:
org.hibernate.orm
hibernate-core
6.6.1.Final
Подробнее здесь: https://stackoverflow.com/questions/790 ... descriptor