DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • What Java Developers Need to Know About Geo-Distributed Databases
  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years
  • Architecture and Code Design, Pt. 1: Relational Persistence Insights to Use Today and On the Upcoming Years
  • Getting Started With JPA/Hibernate

Trending

  • Efficient API Communication With Spring WebClient
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • SaaS in an Enterprise - An Implementation Roadmap
  • Go 1.24+ Native FIPS Support for Easier Compliance
  1. DZone
  2. Data Engineering
  3. Databases
  4. Simplify Java Persistence Using Quarkus and Hibernate Reactive

Simplify Java Persistence Using Quarkus and Hibernate Reactive

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

By 
Daniel Oh user avatar
Daniel Oh
DZone Core CORE ·
Jan. 14, 22 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free

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.

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.

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

Subscribe to bit.ly/danielohtv for learning cloud-native application development with Kubernetes.

Quarkus Hibernate Persistence (computer science) Java (programming language) Relational database Database dev Test data application

Opinions expressed by DZone contributors are their own.

Related

  • What Java Developers Need to Know About Geo-Distributed Databases
  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years
  • Architecture and Code Design, Pt. 1: Relational Persistence Insights to Use Today and On the Upcoming Years
  • Getting Started With JPA/Hibernate

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!