Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Simplify Java persistence using Quarkus and Hibernate Reactive

January 6, 2022
Daniel Oh
Related topics:
Event-DrivenJavaKubernetesQuarkusSystem Design
Related products:
Red Hat OpenShift

Share:

    This tutorial shows how you can simplify reactive Java applications that persist data using the Hibernate ORM with Panache extension in Quarkus.

    Business applications preserve valuable business data in persistence stores such as relational databases. The application's presentation layer usually showcases the data for multiple uses, such as inventory, shopping, subscription, and monitoring. Java provides a core feature, the Java Persistence API (JPA), to manage persistent objects using object-relational mapping (ORM) with databases such as PostgreSQL, MySQL, and Microsoft's SQL Server. However, even when using JPA annotations, you must implement the JPA specifications to handle data transactions.

    Hibernate ORM with Panache

    Hibernate ORM is designed to solve this problem by providing an object-relational mapping framework between Java domain bean classes and schemas in a relational database. The Quarkus framework provides the Hibernate ORM with Panache extension to simplify the persistence layer implementation.

    Benefits

    Hibernate ORM with Panache offers the following benefits over previous options:

    • ID auto-generation
    • No need for getters/setters
    • Static methods provided for access, such as listAll, findById, and find
    • No need for custom queries for basic operations

    Hibernate Reactive

    With the rise of the event-driven architecture, Java developers also need to implement these JPA capabilities in a reactive way to improve application performance and scalability on the event-driven architecture. Hibernate Reactive has recently released version 1.0 with a reactive API for Hibernate ORM support, performing non-blocking interactions with relational databases. The Hibernate Reactive API also lets you manage reactive streams using the SmallRye Mutiny programming library.

    Note: The code for this tutorial is stored in my GitHub repository.

    Add reactive extensions to a Quarkus project

    Run the following Maven command in your project directory to add reactive extensions:

    $ ./mvnw quarkus:add-extension -Dextensions=resteasy-reactive,resteasy-reactive-jackson,hibernate-reactive-panache,reactive-pg-client

    Make sure that the extensions are added to the pom.xml file in the project directory.

    Develop a reactive application with Hibernate Reactive

    The Quarkus dev service for PostgreSQL will pull a PostgreSQL container image and run it automatically in your local environment. Be sure to start a container engine before running Quarkus in Dev Mode. Then, to use the live coding feature, run Quarkus Dev Mode through the following Maven command in the project directory:

    $ ./mvnw quarkus:dev

    The following log messages appear when Quarkus Dev Mode is ready for live coding:

    --
    
    Tests paused
    
    Press [r] to resume testing, [o] Toggle test output, [h] for more options>

    Create a Fruit.java class file in the src/main/java/{Package path} directory. Add the following code to create a new entity bean using Hibernate ORM with Panache:

    @Entity
    @Cacheable
    public class Fruit extends PanacheEntity {
    
        public String name;
    
        public Fruit() {}
    
        public Fruit(String name) {
            this.name = name;
        }
    
    }

    Create a new resource class file (e.g., ReactiveGreetingResource) or update an existing resource class file by adding the following code:

        @GET
        public Uni<List<Fruit>> listAll() { //<1>
            return Fruit.listAll();
        }
    
        @GET
        @Path("{id}")
        public Uni<Fruit> findById(@RestPath Long id) { //<2>
            return Fruit.findById(id);
        }
    
        @POST
        @ReactiveTransactional
        public Uni<Fruit> create(Fruit fruit) { //<3>
            return Fruit.persist(fruit).replaceWith(fruit);
        }
    
        @DELETE
        @Path("{id}")
        @ReactiveTransactional
        public Uni<Void> delete(@RestPath Long id) { //<4>
            return Fruit.deleteById(id).replaceWithVoid();
        }

    Explanations of the annotated lines follow:

    1. Retrieve all Fruit data from the PostgreSQL database using Panache, then return a reactive return stream (Uni).
    2. Retrieve a particular Fruit using Panache, then return a reactive stream (Uni).
    3. Create a new Fruit using a reactive Panache persistence method.
    4. Delete an existing Fruit using a reactive Panache persistence method.

    Add a few test data items to an import.sql file in the src/main/resources directory:

    INSERT INTO fruit(id, name) VALUES (nextval('hibernate_sequence'), 'Cherry');
    INSERT INTO fruit(id, name) VALUES (nextval('hibernate_sequence'), 'Apple');
    INSERT INTO fruit(id, name) VALUES (nextval('hibernate_sequence'), 'Banana');

    Go to the terminal where you are running Quarkus in Dev Mode. Press d to access the Quarkus Dev UI, shown in Figure 1. Take a look at the Hibernate ORM extension box on the right side.

    The Quarkus Dev UI offers a Hibernate ORM extension.
    Figure 1. The Quarkus Dev UI offers a Hibernate ORM extension.

    Click Persistence Units in the extension box. The Dev UI displays the SQL statements that can create or drop the data, as shown in Figure 2.

    You can display the SQL statements that implement persistence.
    Figure 2. You can display the SQL statements that implement persistence.

    Test the reactive application

    Open a new terminal window locally. Invoke the reactive API endpoint using a cURL command or the HTTPie tool. HTTPie could be used as follows:

    $ http :8080/fruits

    The output should look like this:

    HTTP/1.1 200 OK
    Content-Type: application/json
    content-length: 75
    [
        {
            "id": 1,
            "name": "Cherry"
        },
        {
            "id": 2,
            "name": "Apple"
        },
        {
            "id": 3,
            "name": "Banana"
        }
    ]

    Add new data using the following HTTPie command:

    ​​​​​$ echo '{"name":"Orange"}' | http :8080/fruits

    The output should look like this:

    HTTP/1.1 201 Created
    Content-Type: application/json
    content-length: 24
    {
        "id": 4,
        "name": "Orange"
    }

    Now the Orange appears in the fruits data:

    $ http :8080/fruits                           
    HTTP/1.1 200 OK
    Content-Type: application/json
    content-length: 100
    [
        {
            "id": 1,
            "name": "Cherry"
        },
        {
            "id": 2,
            "name": "Apple"
        },
        {
            "id": 3,
            "name": "Banana"
        },
        {
            "id": 4,
            "name": "Orange"
        }
    ]

    Where to learn more

    This guide has shown how Quarkus lets you simplify JPA implementation through the Hibernate ORM with Panache extension. Quarkus also provides awesome features to improve developers’ productivity through continuous testing, the Quarkus command-line interface (CLI), the Dev UI, and Dev Services. Find additional resources at the following articles:

    • Boost throughput with RESTEasy Reactive in Quarkus 2.2
    • Red Hat build of Quarkus 2.2: Simplified Kubernetes-native Java
    • Getting started with Red Hat build of Quarkus
    Last updated: October 18, 2023

    Related Posts

    • Explore Java 17 language features with Quarkus

    • Boost throughput with RESTEasy Reactive in Quarkus 2.2

    • Red Hat build of Quarkus 2.2: Simplified Kubernetes-native Java

    • Why should I choose Quarkus over Spring for my microservices?

    • Build an API using Quarkus from the ground up

    Recent Posts

    • More Essential AI tutorials for Node.js Developers

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue