Java Hibernate Basics: SessionFactory, Session and HQL
Java Hibernate (Hibernate ORM) is the most widely used object-relational mapping framework for Java. It implements the JPA standard you met in the previous lesson, and it also has its own native API built around SessionFactory, Session and HQL, the Hibernate Query Language.
Hibernate is the persistence engine inside Spring Data JPA, Quarkus and many other frameworks, so understanding it helps you read their logs and fix their problems. In this lesson you will map two related entities, build a SessionFactory, save, load, update and delete objects with a Session, write HQL queries, understand lazy loading, and build a small library lending service.
Hibernate and JPA: The Same Ideas with Different Names
Hibernate's native types map one to one onto JPA types. In fact, a Hibernate Session is a JPA EntityManager, and a SessionFactory is an EntityManagerFactory.
| Hibernate native API | JPA standard API | Role |
|---|---|---|
SessionFactory | EntityManagerFactory | Created once; holds mappings and the connection pool |
Session | EntityManager | One unit of work; tracks managed objects |
Transaction | EntityTransaction | Commit or roll back |
| HQL | JPQL | Object-oriented query language (HQL is a superset) |
Configuration / hibernate.properties | persistence.xml | Bootstrapping and settings |
Entities are mapped with the same jakarta.persistence annotations either way. You can freely mix the two styles: for example, call session.unwrap(...) from JPA code, or use JPQL-style queries in a Session.
Adding Hibernate to a Java Project
Use hibernate-core plus a JDBC driver. The examples use the in-memory H2 database.
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>7.4.0.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.232</version>
</dependency>
</dependencies>
How it works:
- Hibernate 7 implements Jakarta Persistence 3.2 and requires Java 17 or newer. Use the latest 7.x release from Maven Central.
- The group id is
org.hibernate.orm. Very old tutorials useorg.hibernate, which stops at version 5.
Note: Hibernate writes INFO log lines when it starts. The outputs in this lesson show only what the programs print with
System.out.
Mapping Hibernate Entities with a Relationship
The examples use a small library: each Book is written by one Author, and an author can have many books. Both classes live in the package com.gocourse.library.
package com.gocourse.library;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
protected Author() { }
public Author(String name) {
this.name = name;
}
public Long getId() { return id; }
public String getName() { return name; }
}
package com.gocourse.library;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private int price; // in rupees
private int copiesAvailable;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Author author; // stored as a foreign key column author_id
protected Book() { }
public Book(String title, int price, int copiesAvailable, Author author) {
this.title = title;
this.price = price;
this.copiesAvailable = copiesAvailable;
this.author = author;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public int getPrice() { return price; }
public int getCopiesAvailable() { return copiesAvailable; }
public void setCopiesAvailable(int copiesAvailable) { this.copiesAvailable = copiesAvailable; }
public Author getAuthor() { return author; }
}
The tables Hibernate generates look like this:
Author Book
+----+---------+ +----+---------------+-------+-----------------+-----------+
| id | name | 1 ---- * | id | title | price | copiesAvailable | author_id |
+----+---------+ +----+---------------+-------+-----------------+-----------+
How it works:
- These are standard JPA annotations, exactly as in the Java JPA lesson.
@ManyToOnesays many books point to one author. Hibernate stores the link as a foreign key column namedauthor_id.fetch = FetchType.LAZYtells Hibernate not to load the author until the code actually needs it.optional = falsemakes the columnNOT NULL.
Building a Hibernate SessionFactory
The native way to start Hibernate is the Configuration class: register the entity classes, set properties and call buildSessionFactory(). A small helper keeps this in one place.
package com.gocourse.library;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public final class HibernateUtil {
private HibernateUtil() { }
public static SessionFactory buildSessionFactory() {
return new Configuration()
.addAnnotatedClass(Author.class)
.addAnnotatedClass(Book.class)
.setProperty("jakarta.persistence.jdbc.url", "jdbc:h2:mem:library;DB_CLOSE_DELAY=-1")
.setProperty("jakarta.persistence.jdbc.user", "sa")
.setProperty("jakarta.persistence.jdbc.password", "")
.setProperty("hibernate.hbm2ddl.auto", "create-drop")
.buildSessionFactory();
}
}
| Property | Example value | Purpose |
|---|---|---|
jakarta.persistence.jdbc.url | jdbc:h2:mem:library | JDBC URL of the database |
jakarta.persistence.jdbc.user / .password | sa / empty | Database login |
hibernate.hbm2ddl.auto | create-drop, update, validate, none | Whether Hibernate creates, updates or only checks tables |
hibernate.show_sql | true | Print every SQL statement Hibernate runs |
hibernate.format_sql | true | Pretty-print the printed SQL |
hibernate.hikari.maximumPoolSize | 10 | Pool size, when the hibernate-hikaricp module is added |
To give every example the same starting data, this helper saves two authors and three books:
package com.gocourse.library;
import org.hibernate.SessionFactory;
public final class LibraryData {
private LibraryData() { }
public static void seed(SessionFactory sessionFactory) {
sessionFactory.inTransaction(session -> {
Author kalki = new Author("Kalki");
Author sujatha = new Author("Sujatha");
session.persist(kalki);
session.persist(sujatha);
session.persist(new Book("Ponniyin Selvan", 650, 3, kalki));
session.persist(new Book("Sivagamiyin Sabatham", 420, 1, kalki));
session.persist(new Book("En Iniya Iyandhira", 250, 2, sujatha));
});
}
}
How it works:
SessionFactoryis expensive to build: Hibernate reads every mapping and prepares SQL. Build it once at startup and close it at shutdown.create-dropcreates the tables when the factory starts and drops them when it closes. It is ideal for tests; production systems usevalidateornonewith a migration tool.inTransaction()opens aSession, begins a transaction, runs your lambda, commits (or rolls back if it throws) and closes the session.- With
IDENTITYkeys, the authors get ids 1 and 2, and the books get ids 1, 2 and 3 in the order they are saved.
Note: Hibernate also accepts the older property names such as
hibernate.connection.url. Thejakarta.persistence.*names shown here are the standard ones and work in both native and JPA bootstrapping.
Saving and Loading Objects with a Hibernate Session
persist() saves a new object and find() loads one by id. fromTransaction() is like inTransaction() but returns a value from the lambda.
package com.gocourse.library;
import org.hibernate.SessionFactory;
public class SaveAndLoad {
public static void main(String[] args) {
try (SessionFactory sessionFactory = HibernateUtil.buildSessionFactory()) {
LibraryData.seed(sessionFactory);
Long newBookId = sessionFactory.fromTransaction(session -> {
Author sujatha = session.find(Author.class, 2L);
Book book = new Book("Karaiyellam Shenbagapoo", 300, 4, sujatha);
session.persist(book);
return book.getId();
});
System.out.println("New book id: " + newBookId);
String summary = sessionFactory.fromTransaction(session -> {
Book book = session.find(Book.class, newBookId);
return book.getTitle() + " by " + book.getAuthor().getName()
+ ", Rs." + book.getPrice() + ", copies: " + book.getCopiesAvailable();
});
System.out.println(summary);
Book missing = sessionFactory.fromTransaction(session -> session.find(Book.class, 99L));
System.out.println("Book 99: " + missing);
}
}
}
Output:
New book id: 4
Karaiyellam Shenbagapoo by Sujatha, Rs.300, copies: 4
Book 99: null
How it works:
- The first transaction loads author 2 and links the new book to it. The book is the fourth one saved, so its id is 4.
- In the second transaction,
book.getAuthor().getName()triggers a small extraSELECTfor the author, because the relationship is lazy. That works because the session is still open. find()returnsnullwhen no row has the id, just like the JPAEntityManager.
Updating and Deleting with a Session
Hibernate saves changes to managed objects automatically at commit (dirty checking). remove() deletes a managed object.
package com.gocourse.library;
import org.hibernate.SessionFactory;
public class UpdateAndDelete {
public static void main(String[] args) {
try (SessionFactory sessionFactory = HibernateUtil.buildSessionFactory()) {
LibraryData.seed(sessionFactory);
// Update: change a managed object, no SQL written by hand
sessionFactory.inTransaction(session -> {
Book book = session.find(Book.class, 1L);
book.setCopiesAvailable(book.getCopiesAvailable() + 2);
});
// Delete: remove a managed object
sessionFactory.inTransaction(session -> {
Book book = session.find(Book.class, 3L);
session.remove(book);
});
sessionFactory.inSession(session -> {
System.out.println("Book 1 copies: " + session.find(Book.class, 1L).getCopiesAvailable());
System.out.println("Book 3 after remove: " + session.find(Book.class, 3L));
});
}
}
}
Output:
Book 1 copies: 5
Book 3 after remove: null
How it works:
- Ponniyin Selvan started with 3 copies. The setter changes the object to 5, and Hibernate writes the
UPDATEwhen the transaction commits. remove()schedules theDELETEfor book 3, which runs at commit.inSession()opens a session without a transaction, which is enough for simple reads.
Note: Older Hibernate code uses
session.save(),session.update(),session.saveOrUpdate()andsession.delete(). These were deprecated in Hibernate 6 and removed in Hibernate 7. Usepersist(), dirty checking ormerge(), andremove()instead.
Writing HQL Queries in Hibernate
HQL (Hibernate Query Language) queries entities and fields, like JPQL, and adds a few extras: for example, you may leave out select when you want whole entities. createSelectionQuery() creates a typed query.
package com.gocourse.library;
import org.hibernate.SessionFactory;
import java.util.List;
public class HqlQueries {
public static void main(String[] args) {
try (SessionFactory sessionFactory = HibernateUtil.buildSessionFactory()) {
LibraryData.seed(sessionFactory);
sessionFactory.inSession(session -> {
// 1. Entities with a parameter; "select b" is optional in HQL
List<Book> cheapBooks = session
.createSelectionQuery("from Book where price < :maxPrice order by title", Book.class)
.setParameter("maxPrice", 500)
.getResultList();
System.out.println("Under Rs.500:");
cheapBooks.forEach(book -> System.out.println(" " + book.getTitle() + " - " + book.getPrice()));
// 2. Navigating a relationship in the where clause
List<String> kalkiTitles = session
.createSelectionQuery("select b.title from Book b where b.author.name = :name order by b.title", String.class)
.setParameter("name", "Kalki")
.getResultList();
System.out.println("By Kalki: " + kalkiTitles);
// 3. A single aggregate value
Long totalCopies = session
.createSelectionQuery("select sum(b.copiesAvailable) from Book b", Long.class)
.getSingleResult();
System.out.println("Total copies: " + totalCopies);
// 4. Several values per row, grouped
List<Object[]> perAuthor = session
.createSelectionQuery("select a.name, count(b) from Book b join b.author a group by a.name order by a.name", Object[].class)
.getResultList();
for (Object[] row : perAuthor) {
System.out.println(row[0] + " has " + row[1] + " book(s)");
}
});
}
}
}
Output:
Under Rs.500:
En Iniya Iyandhira - 250
Sivagamiyin Sabatham - 420
By Kalki: [Ponniyin Selvan, Sivagamiyin Sabatham]
Total copies: 6
Kalki has 2 book(s)
Sujatha has 1 book(s)
How it works:
from Book where price < :maxPriceis valid HQL withoutselect. Two books cost less than 500, sorted by title.b.author.namewalks the relationship; Hibernate adds the SQL join for you.sum()of anintfield returns aLongin HQL. The copies are3 + 1 + 2 = 6.- A query that selects more than one value returns each row as an
Object[], in the order of theselectlist.
| HQL feature | Example |
|---|---|
| Named parameter | where b.price < :maxPrice |
| Navigate a relation | where b.author.name = :name |
| Explicit join | from Book b join b.author a |
| Join fetch (load related data now) | from Book b join fetch b.author |
| Aggregates | count(b), sum(...), avg(...), max(...) |
| Grouping | group by a.name having count(b) > 1 |
Lazy Loading and LazyInitializationException
A lazy relationship is loaded only when you touch it, and only while the session is open. Touching it after the session closes throws LazyInitializationException, one of the most common Hibernate errors.
package com.gocourse.library;
import org.hibernate.LazyInitializationException;
import org.hibernate.SessionFactory;
public class LazyLoadingDemo {
public static void main(String[] args) {
try (SessionFactory sessionFactory = HibernateUtil.buildSessionFactory()) {
LibraryData.seed(sessionFactory);
// The session closes when fromTransaction returns
Book detachedBook = sessionFactory.fromTransaction(session -> session.find(Book.class, 1L));
System.out.println("Title: " + detachedBook.getTitle());
try {
System.out.println("Author: " + detachedBook.getAuthor().getName());
} catch (LazyInitializationException e) {
System.out.println("Error: " + e.getClass().getSimpleName());
}
// Fix: load the author in the same query with join fetch
Book bookWithAuthor = sessionFactory.fromTransaction(session -> session
.createSelectionQuery("from Book b join fetch b.author where b.id = :id", Book.class)
.setParameter("id", 1L)
.getSingleResult());
System.out.println("Author (join fetch): " + bookWithAuthor.getAuthor().getName());
}
}
}
Output:
Title: Ponniyin Selvan
Error: LazyInitializationException
Author (join fetch): Kalki
How it works:
find()loads the book's own columns. Because the author is lazy,getAuthor()returns a proxy: a placeholder that knows only the author's id.- Calling
getName()on the proxy after the session has closed cannot run a query, so Hibernate throwsLazyInitializationException. join fetch b.authorloads the book and its author in a single SQL query, so the author is ready to use after the session closes.
Note: Do not "fix" this error by switching every relationship to
FetchType.EAGER. Eager loading fetches related data even when you do not need it and can turn one query into dozens. Keep relationships lazy and usejoin fetchin the queries that need the related data.
Real-World Example: A Library Lending Service
This service puts the pieces together: one SessionFactory, a short transaction per operation, business rules in Java, dirty checking for updates and an HQL report.
package com.gocourse.library;
import org.hibernate.SessionFactory;
import java.util.List;
public class LibraryApp {
static class LendingService {
private final SessionFactory sessionFactory;
LendingService(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
String borrow(long bookId) {
return sessionFactory.fromTransaction(session -> {
Book book = session.find(Book.class, bookId);
if (book == null) {
return "No book with id " + bookId;
}
if (book.getCopiesAvailable() == 0) {
return "Sorry, '" + book.getTitle() + "' is not available";
}
book.setCopiesAvailable(book.getCopiesAvailable() - 1); // UPDATE at commit
return "Borrowed '" + book.getTitle() + "', copies left: " + book.getCopiesAvailable();
});
}
String giveBack(long bookId) {
return sessionFactory.fromTransaction(session -> {
Book book = session.find(Book.class, bookId);
book.setCopiesAvailable(book.getCopiesAvailable() + 1);
return "Returned '" + book.getTitle() + "', copies now: " + book.getCopiesAvailable();
});
}
void printStockReport() {
List<Object[]> rows = sessionFactory.fromTransaction(session -> session
.createSelectionQuery("""
select a.name, count(b), sum(b.copiesAvailable)
from Book b join b.author a
group by a.name
order by a.name""", Object[].class)
.getResultList());
System.out.println("Author Titles Copies");
for (Object[] row : rows) {
System.out.printf("%-11s %6s %7s%n", row[0], row[1], row[2]);
}
}
List<String> outOfStock() {
return sessionFactory.fromTransaction(session -> session
.createSelectionQuery("select b.title from Book b where b.copiesAvailable = 0 order by b.title", String.class)
.getResultList());
}
}
public static void main(String[] args) {
try (SessionFactory sessionFactory = HibernateUtil.buildSessionFactory()) {
LibraryData.seed(sessionFactory);
LendingService lending = new LendingService(sessionFactory);
System.out.println(lending.borrow(2)); // the only copy
System.out.println(lending.borrow(2)); // none left
System.out.println(lending.borrow(99)); // unknown id
System.out.println(lending.borrow(1));
System.out.println("Out of stock: " + lending.outOfStock());
System.out.println(lending.giveBack(2));
System.out.println("Out of stock: " + lending.outOfStock());
lending.printStockReport();
}
}
}
Output:
Borrowed 'Sivagamiyin Sabatham', copies left: 0
Sorry, 'Sivagamiyin Sabatham' is not available
No book with id 99
Borrowed 'Ponniyin Selvan', copies left: 2
Out of stock: [Sivagamiyin Sabatham]
Returned 'Sivagamiyin Sabatham', copies now: 1
Out of stock: []
Author Titles Copies
Kalki 2 3
Sujatha 1 2
How it works:
- One factory, short sessions.
mainbuilds theSessionFactoryonce. Every service method opens a session throughfromTransaction(), does one job and closes it, so no session lives longer than a single operation. - Business rules in Java.
borrow()checks for a missing book and for zero copies before changing anything. The second request for book 2 is refused because the first one took the only copy. - Updates by dirty checking. Neither
borrow()norgiveBack()writes SQL. ChangingcopiesAvailableon the managedBookis enough; Hibernate writes theUPDATEat commit. - HQL for reporting. The report uses a Java text block for a readable multi-line query. Kalki has 2 titles with
2 + 1 = 3copies after the lending activity, and Sujatha has 1 title with 2 copies.
Note: Two users borrowing the last copy at the same moment could both see
1and both succeed. Real lending systems prevent this with optimistic locking: add a@Versionfield toBook, and Hibernate will reject the second, stale update.
Hibernate runs every one of these operations over JDBC, so the Java connection pooling and Java JDBC Transactions lessons still apply underneath. With entities and databases covered, the tutorial now moves to organizing larger Java applications, starting with packages.