Hibernate ORM 6 introduces several changes to its API compared to previous versions, especially in how SessionFactory
and Session
are used due to compliance with Jakarta EE and its updated imports (jakarta.persistence.*
).
Here’s a simple guide to using SessionFactory
and Session
in Hibernate 6:
1. Add Hibernate Dependencies
Make sure to include the Hibernate 6 dependencies in your project. If you’re using Maven, the dependency would look like this:
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.4.Final</version>
</dependency>
2. Configure Hibernate
Use or Properties
for configuration:hibernate.cfg.xml
Example: hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/your_database</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
Alternatively, use Java configuration with Properties
:
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.connection.driver_class", "org.postgresql.Driver");
properties.put("hibernate.connection.url", "jdbc:postgresql://localhost:5432/your_database");
properties.put("hibernate.connection.username", "your_username");
properties.put("hibernate.connection.password", "your_password");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
3. Create a SessionFactory
Starting with Hibernate 6, the SessionFactory
should be built using the StandardServiceRegistryBuilder
and MetadataSources
.
Here’s an example:
Using hibernate.cfg.xml
:
package org.kodejava.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
// Build the ServiceRegistry using hibernate.cfg.xml
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml") // Loads hibernate.cfg.xml by default
.build();
try {
// Build SessionFactory
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(registry);
throw new ExceptionInInitializerError("SessionFactory build failed: " + e.getMessage());
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
Using Java configuration with Properties
:
package org.kodejava.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
// Create Hibernate properties
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.connection.driver_class", "org.postgresql.Driver");
properties.put("hibernate.connection.url", "jdbc:postgresql://localhost:5432/your_database");
properties.put("hibernate.connection.username", "your_username");
properties.put("hibernate.connection.password", "your_password");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
// Build the ServiceRegistry
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(properties)
.build();
try {
// Build SessionFactory
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(registry);
throw new ExceptionInInitializerError("SessionFactory build failed: " + e.getMessage());
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
4. Use SessionFactory
to Get a Session
A Session
represents a single unit of work with the database. In Hibernate 6, the usage involves a similar pattern to previous versions.
package org.kodejava.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class App {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
// Obtain a session
try (Session session = sessionFactory.openSession()) {
// Begin transaction
session.beginTransaction();
// Perform operations (e.g., save entities)
MyEntity entity = new MyEntity();
entity.setName("Example");
session.persist(entity);
// Commit the transaction
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Shutdown the session factory
HibernateUtil.shutdown();
}
}
}
5. Entity Example
Ensure your entity classes are annotated correctly with Jakarta Persistence annotations (jakarta.persistence.*
).
package org.kodejava.hibernate;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Key Updates in Hibernate 6
- Jakarta Imports: Hibernate moved from
javax.persistence.*
tojakarta.persistence.*
. - Default Configuration: The APIs are adaptive, but the configuration process is largely unchanged.
- Session Persistence: The
Session.persist(Object)
method is preferred over deprecated methods likesave(Object)
.
By following these steps, you can effectively use SessionFactory
and Session
in Hibernate 6 for your application.