I am new to Java (and Hibernate) and for learning Java I want to create plain Java app with simple CRUD operations using database. I found article with setting up hibernate so I followed it and the result is below:
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;
}
}
And in Main.java I put:
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();
}
}
But I am constantly getting error:
Exception in thread "main" org.hibernate.UnknownEntityTypeException: Unable to locate entity descriptor: com.model.Student
I found that the problem can be with using older hibernate version, but in my case in my pom.xml I have:
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.6.1.Final</version>
</dependency>
This is because Hibernate doesn't know about your Student
entity.
Since Hibernate 5 the Configuration.configure()
method is broken. If you want to add mapping via hibernate.cfg.xml
, use MetadataSources:
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
Or you can simply register your entity with Configuration.addAnnotatedClass()
configuration.addAnnotatedClass(Student.class);