Access a database with JPA and Hibernate Reactive
Learn how to use Hibernate Reactive with the Micronaut Framework.
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Java.
In this guide, we will write a Micronaut application that exposes some REST endpoints and stores data in a database using JPA and Hibernate.
What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately
Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-app example.micronaut.micronautguide --build=maven --lang=java|
Note
|
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.
Data Source Configuration
Add the following dependencies:
JPA configuration
Add the following snippet to src/main/resources/application.properties to configure JPA:
jpa.default.reactive=true
jpa.default.properties.hibernate.connection.db-type=mysql
jpa.default.properties.hibernate.hbm2ddl.auto=create-drop
jpa.default.properties.hibernate.show_sql=trueDomain
Create the domain entities:
package example.micronaut.domain;
import io.micronaut.serde.annotation.Serdeable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
import static jakarta.persistence.GenerationType.AUTO;
@Serdeable
@Entity
@Table(name = "genre")
public class Genre {
@Id
@GeneratedValue(strategy = AUTO)
private Long id;
@NotNull
@Column(name = "name", nullable = false, unique = true)
private String name;
@JsonIgnore
@OneToMany(mappedBy = "genre")
private Set<Book> books = new HashSet<>();
public Genre() {}
public Genre(@NotNull String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "Genre{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}The previous domain has a OneToMany relationship with the domain Book.
package example.micronaut.domain;
import io.micronaut.serde.annotation.Serdeable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import static jakarta.persistence.GenerationType.AUTO;
@Serdeable
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = AUTO)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "isbn", nullable = false)
private String isbn;
@ManyToOne
private Genre genre;
public Book() {}
public Book(@NotNull String isbn,
@NotNull String name,
Genre genre) {
this.isbn = isbn;
this.name = name;
this.genre = genre;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", isbn='" + isbn + '\'' +
", genre=" + genre +
'}';
}
}Application Configuration
Create an interface to encapsulate the application configuration settings:
package example.micronaut;
public interface ApplicationConfiguration {
int getMax();
}Like Spring Boot and Grails, in Micronaut applications you can create typesafe configuration by creating classes that are annotated with @ConfigurationProperties.
Create an ApplicationConfigurationProperties class:
You can override max if you add to your src/main/resources/application.properties:
application.max=50Repository Access
Next, create a repository interface to define the operations to access the database:
package example.micronaut;
import example.micronaut.domain.Genre;
import io.micronaut.core.annotation.NonNull;
import org.reactivestreams.Publisher;
import jakarta.validation.constraints.NotBlank;
import java.util.Optional;
public interface GenreRepository {
Publisher<Optional<Genre>> findById(long id);
Publisher<Genre> save(@NotBlank String name);
Publisher<Genre> saveWithException(@NotBlank String name);
void deleteById(long id);
Publisher<Genre> findAll(@NonNull SortingAndOrderArguments args);
Publisher<Integer> update(long id, @NotBlank String name);
}And the implementation:
Controller
Micronaut validation is built on the standard framework – JSR 380, also known as Bean Validation 2.0. Micronaut Validation has built-in support for validation of beans that are annotated with jakarta.validation annotations.
To use Micronaut Validation, you need the following dependencies:
<!-- Add the following to your annotationProcessorPaths element -->
<path>
<groupId>io.micronaut.validation</groupId>
<artifactId>micronaut-validation-processor</artifactId>
</path>
<dependency>
<groupId>io.micronaut.validation</groupId>
<artifactId>micronaut-validation</artifactId>
<scope>compile</scope>
</dependency>Alternatively, you can use Micronaut Hibernate Validator, which uses Hibernate Validator; a reference implementation of the validation API.
Create two classes to encapsulate Save and Update operations:
package example.micronaut;
import io.micronaut.serde.annotation.Serdeable;
import jakarta.validation.constraints.NotBlank;
@Serdeable
public class GenreUpdateCommand {
private long id;
@NotBlank
private String name;
public GenreUpdateCommand(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}Create a POJO to encapsulate Sorting and Pagination:
Create GenreController, a controller which exposes a resource with the common CRUD operations:
Writing Tests
Create a test to verify the CRUD operations:
Testing the Application
To run the tests:
./mvnw testTest Resources
When the application is started locally, either under test or while running locally, resolution of the datasource URL is detected and the Test Resources service will start a local MySQL docker container, and inject the properties required to use this as the datasource.
For more information, see the JDBC section or R2DBC section of the Test Resources documentation.
Using MySQL
When you move to production, you will need to configure the properties injected by Test Resources to point at your real production database. This can be done via environment variables like so:
export JPA_DEFAULT_PROPERTIES_HIBERNATE_CONNECTION_URL=jdbc:mysql://localhost:5432/micronaut
export JPA_DEFAULT_PROPERTIES_HIBERNATE_CONNECTION_USERNAME=dbuser
export JPA_DEFAULT_PROPERTIES_HIBERNATE_CONNECTION_PASSWORD=theSecretPasswordRun the application. If you look at the output you can see that the application uses MySQL:
Running the Application
To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.
..
...
16:31:01.155 [main] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
....Connect to your MySQL database, and you will see both genre and book tables.
Save one genre, and your genre table will now contain an entry.
curl -X "POST" "http://localhost:8080/genres" \
-H 'Content-Type: application/json; charset=utf-8' \
-d $'{ "name": "music" }'Next Steps
Read more about the Configurations for Data Access section in the Micronaut documentation.
Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
License
|
Note
|
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images). |