Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Data with Panache

Hibernate ORM with Panache

Set up a database in Quarkus with Hibernate ORM and Panache: datasource config, Dev Services, active record entities, persist, find, delete and the persistence context.

Sooner or later your service needs a database. In Quarkus the usual stack is Hibernate ORM (the object-relational mapper behind JPA) made friendlier by Panache, a layer that removes most of the boilerplate. Panache offers two styles: active record, where the entity itself has methods like persist() and findById(), and the repository style, covered in the next lesson.

The real Quarkus, Hibernate and database code on this page is read-only. The two runnable stand-ins are plain Java: one models the active record pattern, the other models how Hibernate notices changes to a managed entity.

Setting up

Add the extensions (the JDBC driver extension depends on your database):

XML
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>

Configure the datasource in application.properties:

PROPERTIES
quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=bookshop
quarkus.datasource.password=${DB_PASSWORD}
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/bookshop

# dev and test: let Hibernate build the schema
%dev.quarkus.hibernate-orm.database.generation=drop-and-create
%test.quarkus.hibernate-orm.database.generation=drop-and-create

In dev and test mode you can leave the URL, user and password out entirely. Dev Services starts a throwaway PostgreSQL container for you (Docker required) and fills in the connection, as described in Dev Mode and Dev Services. In production you set the real URL and secrets through environment variables or a secrets store.

An active record entity

Java
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;

@Entity
public class Book extends PanacheEntity {

    @Column(nullable = false, length = 120)
    public String title;

    public String author;

    public int year;

    public static Book byTitle(String title) {
        return find("title", title).firstResult();
    }
}

PanacheEntity already declares public Long id with a generated sequence value. Fields are public on purpose: Quarkus rewrites field access into getter/setter calls at build time, so you keep Hibernate's lazy loading and dirty checking while writing less code. You can still add getters and setters when you want logic in them. If you need your own id type or generator, extend PanacheEntityBase and declare the id yourself.

Using the entity looks like this:

Java
@Path("/books")
@Produces(MediaType.APPLICATION_JSON)
public class BookResource {

    @GET
    public List<Book> all() {
        return Book.listAll();
    }

    @GET
    @Path("/{id}")
    public Book one(@RestPath Long id) {
        Book book = Book.findById(id);
        if (book == null) {
            throw new NotFoundException();
        }
        return book;
    }

    @POST
    @Transactional
    public RestResponse<Book> create(Book input) {
        input.persist();
        return RestResponse.status(201, input);
    }

    @DELETE
    @Path("/{id}")
    @Transactional
    public void delete(@RestPath Long id) {
        Book.deleteById(id);
    }
}

Methods that change data need a transaction: @Transactional, explained in Transactions and Flyway. Reads can run without one.

The static methods you saw come from the Panache base class: listAll(), findById(id), find(query, params), list(...), count(), delete(...), deleteAll(), deleteById(id), update(...) and stream(...). Instance methods include persist(), delete() and isPersistent().

The active record idea, modelled

Java statics are not inherited polymorphically, so Panache uses build-time enhancement to give every entity its own typed findById. The stand-in below shows the pattern with a hand-written store per class: the entity knows how to save and load itself.

Java Stand-in: the active record pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The persistence context

Hibernate does not run SQL the moment you set a field. Inside a transaction it keeps a persistence context: a map of the entities it has loaded or persisted, plus a snapshot of how they looked. When the transaction commits, Hibernate compares each entity to its snapshot (dirty checking) and writes UPDATE statements for the changes. This is why you can write:

Java
@PUT
@Path("/{id}")
@Transactional
public Book rename(@RestPath Long id, String newTitle) {
    Book book = Book.findById(id);   // managed entity
    book.title = newTitle;           // no save() call needed
    return book;                     // UPDATE runs at commit
}

There is no update() call. The entity is managed, so the change is tracked. An entity outside a transaction is detached: changes to it are not written.

Java Stand-in: dirty checking at commit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Panache in one picture

Entity A Java class mapped to a table.
Panache Adds persist, find and delete.
Hibernate Tracks changes and writes SQL.
Database PostgreSQL, MySQL and others.

You write entities, Quarkus wires the rest.

1 / 2

Active record or repository?

Active record is short and easy to read, and it is excellent for small services. The repository style separates data access from the entity, which many teams prefer for larger code bases or when they mock the data layer in tests. Both are first-class in Quarkus and even mix in one project. The next lesson uses repositories.

Never return entities straight from an endpoint when they have lazy relations or internal fields. Map them to DTO records, as shown in Relationships and DTOs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an entity that extends PanacheEntity already have?

    PanacheEntity supplies the id (generated) plus persist(), findById(), listAll() and more.
  2. 2. Why do you not need to call save() after changing a field of a managed entity inside a transaction?

    The persistence context compares entities with their snapshots at commit and issues UPDATE statements for differences.
  3. 3. What provides a database automatically in dev and test mode when no URL is configured?

    Dev Services starts a container (for example PostgreSQL) and configures the connection.
  4. 4. When should you extend PanacheEntityBase instead of PanacheEntity?

    PanacheEntityBase has the methods but no id, so you declare the id yourself.

Summary

  • Add quarkus-hibernate-orm-panache and a JDBC extension, then configure the datasource; Dev Services supplies a database in dev and test.
  • Active record entities extend PanacheEntity and use persist(), findById(), listAll(), deleteById().
  • Public fields are fine: Quarkus enhances them at build time.
  • A managed entity inside a transaction is dirty-checked and updated at commit with no save().

Next: Panache Repositories and Queries