Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
107 views

Hibernate Reactive - Getting Started Guide

Hibernate reactivo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views

Hibernate Reactive - Getting Started Guide

Hibernate reactivo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

14/9/2021 Hibernate Reactive - Getting Started Guide

Hibernate Reactive: Getting Started Guide

Hibernate Reactive – Getting Started Guide


By Thorben Janssen

tweet share share share email


         
If you want to implement a reactive application, you not only need to adapt your
Spring Data JPA Course
way of thinking and switch to reactive libraries for your business layer. You also x
Price
need Increases
to access In in a reactive way. One way to do that is to use
your database
Hibernate Reactive. It’s based on Vert.X and implements the well-known concepts
of JPA and Hibernate ORM D 03  : 15  : 33  : 43 
based on theHreactive programming
M S
paradigm.

Sign Up Now!
Contents [hide]

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 1/18
14/9/2021 Hibernate Reactive - Getting Started Guide

1 Dependencies and Configuration


2 Entity Mappings
3 Working with Hibernate Reactive
3.1 Getting a Hibernate SessionFactory
3.2 Persisting a New Entity
3.3 Querying Entities
3.4 Initializing Lazy Associations
3.4.1 JOIN FETCH Clauses
3.4.2 Programmatic Initialization
4 Updating Entities
5 Removing Entities
6 Conclusion

Dependencies and Configuration


Before you can use Hibernate Reactive in your application, you need to add the
required dependencies and configure it.

The only 2 dependencies you need are Hibernate Reactive and one of Vert.X
reactive database clients. When you add these dependencies, make sure that
Hibernate Reactive supports your chosen Vert.X version. Otherwise, you will get
some strange exceptions when executing your test cases.

In the examples of this post, I will use a PostgreSQL database and therefore use
Vert.X PostgreSQL client.
Spring Data JPA Course x
Price
1
2 Increases
<project>
... In
3
4
5
6
03  : 15  : 33  : 43 
<dependencies>
D
<dependency> H M S
<groupId>org.hibernate.reactive</groupId>
7 <artifactId>hibernate-reactive-core</artifactId
8 Sign Up Now!
<version>${hibernate.version}</version>
9 </dependency>
https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 2/18
14/9/2021 Hibernate Reactive - Getting Started Guide

10 <dependency>
11 <groupId>io.vertx</groupId>
12 <artifactId>vertx-pg-client</artifactId>
13 <version>${vertx.version}</version>
14 </dependency>
15 ...
16 </dependencies>
17 </project>

You can use almost the same persistence.xml configuration for your Hibernate
Reactive project as you use in your Hibernate ORM projects. The only difference is
that you need to reference
org.hibernate.reactive.provider.ReactivePersistenceProvider as your provider.

1 <persistence>
2 <persistence-unit name="my-persistence-unit">
3 <description>Hibernate Reactive configuration - tho
4 <provider>org.hibernate.reactive.provider.ReactiveP
5 <exclude-unlisted-classes>false</exclude-unlisted-c
6 <properties>
7 <property name="hibernate.jdbc.time_zone" value
8
9 <property name="javax.persistence.jdbc.driver"
10 <property name="javax.persistence.jdbc.url" val
11 <property name="javax.persistence.jdbc.user" va
12 <property name="javax.persistence.jdbc.password
13
14 <property name="javax.persistence.schema-genera
15 <property name="javax.persistence.sql-load-scri
16 </properties>
17 </persistence-unit>
18 </persistence>

Entity Mappings
Spring Data JPA Course x
Price
After you Increases In dependencies, you can start working on your entity
added the required
mappings. As described earlier, Hibernate Reactive is based on Hibernate ORM,
which implements the JPA D
03  : 15  : 33  : 43 
specification.
HAs of now,M
Hibernate Reactive
S supports
most of Hibernate ORM’s mapping annotations, and you can reference my previous
articles about Hibernate and JPA, ifSign
you have any questions.
Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 3/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Commonly used annotations that are currently not supported are @ManyToMany
and @ElementCollection. But that’s not a huge issue. I recommend avoiding
@ElementCollection in general. And instead of a many-to-many association, you
can map the association table to its own entity class with 2 many-to-one
associations.

All entities need to fulfill the JPA requirements. Here you can see an example of an
entity that maps information in the ChessPlayer database table. It maps the first
and last name of the player, their date of birth, and 2 associations to the games
they played as white and black. The mapping annotations on the id attribute mark
it as the primary key attribute and tell Hibernate to use a database sequence to
generate unique primary key values.

1 @Entity
2 public class ChessPlayer {
3
4 @Id
5 @GeneratedValue(strategy = GenerationType.SEQUENCE, gen
6 @SequenceGenerator(name = "player_seq", sequenceName =
7 private Long id;
8
9 private String firstName;
10
11 private String lastName;
12
13 private LocalDate birthDate;
14
15 @OneToMany(mappedBy = "playerWhite")
16 private Set<ChessGame> gamesWhite;
17
18 @OneToMany(mappedBy = "playerBlack")
19 private Set<ChessGame> gamesBlack;
Spring Data
20
21 JPA Course
@Version x
Price Increases
22
23 In
private int version;

24 public Long getId() {


25
26
27
} 03  : 15  : 33  M : 43  S
return id;
D H
28 public String getFirstName() {
29 Sign Up Now!
return firstName;
30 }
https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 4/18
14/9/2021 Hibernate Reactive - Getting Started Guide

31
32 public void setFirstName(String firstName) {
33 this.firstName = firstName;
34 }
35
36 // more getter and setter methods
37 }

Working with Hibernate Reactive

Based on your entity mappings, you can then implement your database access.
Similar to the entity mapping annotations, Hibernate Reactive adapted the
SessionFactoy, Session, and Query interfaces. You can decide if you want to use
them based on the Mutiny or CompletionStage API. In the following sections, I will
provide you an example for both APIs.

Spring Data JPA Course x


Price Increases In
03  D : 15  H : 33  M : 43  S
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 5/18
14/9/2021 Hibernate Reactive - Getting Started Guide

2 Ebooks 
to boost your Hibernate skills

Sign up below to join my newsletter and to get your free


ebooks:

Java 8 Support in Hibernate 5

Native Queries with Hibernate

Your email address

Subscribe

I will collect, use and protect your data in accordance with my Privacy
Spring Data JPA Coursepolicy. x
Price Increases In
03  D : 15  H : 33  M : 43  S
Getting a Hibernate SessionFactory
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 6/18
14/9/2021 Hibernate Reactive - Getting Started Guide

As explained earlier, the configuration is based on JPA, and you can use the
standard JPA APIs to get your EntityManagerFactory. In the next step, you need to
decide which API you want to use and unwrap a Mutiny.SessionFactory:

1 EntityManagerFactory emf = Persistence.createEntityManagerFa


2 SessionFactory factory = emf.unwrap(Mutiny.SessionFactory.cl

or a Stage.SessionFactory:

1 EntityManagerFactory emf = Persistence.createEntityManagerFa


2 SessionFactory factory = emf.unwrap(Stage.SessionFactory.cla

In the next step, you can then use the SessionFactory to get a Session and execute
your operations. The reactive Session interfaces offer the same methods that you
know from Hibernate ORM.

Persisting a New Entity

To persist a new ChessPlayer in your database, you need to instantiate a new


ChessPlayer entity object, call the withTransaction method on your SessionFactory
to get a Session with an active transaction, and call the persist method. Hibernate
Reactive will then flush your new entity and commit the transaction automatically.

Mutiny API

1 ChessPlayer p = new ChessPlayer();


Spring Data JPA Course
2
3
p.setFirstName("Thorben");
p.setLastName("Janssen"); x
Pricefactory.withTransaction((session,
4
5 Increases In tx) -> session.persist(p))
6 .await()
7
03  D : 15  H : 33  M : 43  S
.indefinitely();

CompletionStage API
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 7/18
14/9/2021 Hibernate Reactive - Getting Started Guide

1 ChessPlayer p = new ChessPlayer();


2 p.setFirstName("Thorben");
3 p.setLastName("Janssen");
4
5 factory.withTransaction((session, tx) -> session.persist(p))
6 .toCompletableFuture()
7 .join();

Querying Entities

Using Hibernate Reactive, you can query your entities in the same way you do with
Hibernate ORM. You can call the find method on your Session to get an entity by its
primary key or write queries using JPQL, Criteria API, and native SQL statements.

Mutiny API

1 factory.withSession(
2 session -> session.find(ChessGame.class, 1L)
3 ).await().indefinitely();

CompletionStage API

1 factory.withSession(
2 session -> session.find(ChessGame.class, 1L)
3 ).toCompletableFuture().join();

Initializing Lazy Associations

But there is one important difference. Hibernate Reactive doesn’t transparently


fetch lazy associations. You either need to fetch them as part of your query using a
Spring Data JPA Course
JOIN FETCH clause or an EntityGraph, or you need to initialize the association x
Price Increases In
programmatically.

JOIN FETCH Clauses 03  D : 15  H : 33  M : 43  S


Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 8/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Let’s use a JOIN FETCH clause first. It’s the recommended approach because it
provides better performance than the programmatic initialization and is easier to
define than an EntityGraph.

Mutiny API

1 factory.withSession(session -> session.createQuery("SELECT g


2 .setParameter("gameId",
3 .getSingleResult()
4 .invoke(game -> System.o
5
6
7
8 ).await().indefinitely();

CompletionStage API

1 factory.withSession(session -> session.createQuery("SELECT g


2 .setParameter("gameId",
3 .getSingleResult()
4 .thenAccept(game -> Syst
5
6
7
8 ).toCompletableFuture().join();

Programmatic Initialization

If you already retrieved an entity from the database and want to fetch an
association programmatically, you need to call the Session.fetch method.

Spring Data JPA Course


Mutiny API x
Price Increases In
1 factory.withSession(
2
3
4
03  : 15  : 33  : 43 
session -> session.find(ChessGame.class, 1L)
D H M -> session.fetch(game.g
.chain(game S
.chain(white
5 .invoke(black
6 Sign Up Now!
7
https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 9/18
14/9/2021 Hibernate Reactive - Getting Started Guide

8
9
10 ).await().indefinitely();

CompletionStage API

1 factory.withSession(session -> session.find(ChessGame.class,


2 .thenCompose(game ->
3 session.fetch(game.getPlayerWhite())
4 .thenCompose(white -> sessio
5 .thenAccept(black -> System
6 white.getFir
7 " played aga
8 black.getFir
9 ).toCompletableFuture().join();

Updating Entities
The easiest way to update entity objects is to query them from the database and
call one or more of their setter methods. When you do that, make sure to call the
withTransaction method on your SessionFactory to get a Session instance with an
associated transaction. Hibernate Reactive will then handle the required flush and
commit operations for you.

Mutiny API

1 factory.withTransaction((session, tx) -> session.createQuery


2 .getResultList()
3 .invoke(players -> players.forEach(p
4 ).await().indefinitely();
Spring Data JPA Course x

Price Increases In
CompletionStage API

1
2
3
03  : 15  : 33  : 43 
factory.withTransaction((session, tx) -> session.createQuery
D H M
.getResultList() S
.thenAccept(players -> players.forEa
4 ).toCompletableFuture().join();
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 10/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Removing Entities

And you can remove entities in a similar way. You get a Session instance with an
associated transaction, query the entities from the database and call the
Session.remove method for each of them.

Mutiny API

1 factory.withTransaction((session, tx) -> session.find(ChessG


2 .call(game -> session.remove(game))
3 ).await().indefinitely();

CompletionStage API

1 factory.withTransaction((session, tx) -> session.find(ChessG


2 .thenAccept(game -> session.remove(g
3 ).toCompletableFuture().join();

Conclusion

If you’re already familiar with JPA and Hibernate ORM and want to implement a
reactive application, then you should try Hibernate Reactive. It enables you to use
the same mapping annotations and APIs that you already know from Hibernate
ORM.

There are also several differences, like the fetching of lazy associations and the

Spring Data JPA Course


missing support for a few mapping annotations. But these can be easily handled,
x
and they shouldn’t prevent you from giving Hibernate Reactive a try.
Price Increases In
03  D : 15  H : 33  M : 43  S
tweet share share share email
         

TAGS
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 11/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Spring Data JPA Course x


Price Increases In
03  D : 15  H : 33  M : 43  S
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 12/18
14/9/2021 Hibernate Reactive - Getting Started Guide

ABOUT THE AUTHOR

Thorben is an independent consultant, international speaker, and trainer specialized in


Spring Data JPA
solving Courseproblems with JPA and Hibernate.
Java persistence x
Price Increases In
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70
solutions to common Hibernate problems.

03  D : 15  H : 33  M : 43  S


Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 13/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Books and Courses

Spring Data JPA Course x


Price Increases In
03  D : 15  H : 33  M : 43  S
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 14/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Spring Data JPA Course x


Price Increases In
03  D : 15  H : 33  M : 43  S
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 15/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Coaching and Consulting


Spring Data JPA Course x
Price Increases In
03  D : 15  H : 33  M : 43  S
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 16/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Leave a Reply

Your email address will not be published. Required fields are marked

Comment

Name *

Email *

Spring Data JPA Course x


Price Increases In
Website
03  D : 15  H : 33  M : 43  S
Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 17/18
14/9/2021 Hibernate Reactive - Getting Started Guide

Save my name, email, and website in this browser for the next time I comment.

POST COMMENT

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Jachu
Is hibernate-reactive supported by Spring Data as well ?

Reply

Thorben Janssen
No, it isn’t. The Spring team has its own library for reactive database access
(Spring Data R2DBC) and (as far as I know) has no immediate plans to
support another one.

Regards,
Thorben

Reply

Spring Data JPA Course x

Price Increases In Copyright 2021 Thorben Janssen, all rights reserved.


Disclaimer     Privacy policy     Imprint

03  D : 15  H : 33  M : 43  S


Sign Up Now!

https://thorben-janssen.com/hibernate-reactive-getting-started-guide/ 18/18

You might also like