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 Kotlin.
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=gradle --lang=kotlin|
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.GenerationType
import jakarta.persistence.Table
import jakarta.persistence.Id
import jakarta.persistence.OneToMany
@Serdeable
@Entity
@Table(name = "genre")
class Genre(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false, updatable = false)
val id: Long?,
@Column(name = "name", nullable = false)
var name: String
) {
@JsonIgnore
@OneToMany(mappedBy = "genre")
var books: MutableSet<Book> = mutableSetOf()
}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.GenerationType
import jakarta.persistence.Table
import jakarta.persistence.Id
import jakarta.persistence.ManyToOne
@Serdeable
@Entity
@Table(name = "book")
class Book(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Long,
@Column(name = "name", nullable = false)
var name: String,
@Column(name = "isbn", nullable = false)
var isbn: String
) {
@ManyToOne
var genre: Genre? = null
}Application Configuration
Create an interface to encapsulate the application configuration settings:
package example.micronaut
interface ApplicationConfiguration {
val max: Int
}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 org.reactivestreams.Publisher
import jakarta.validation.constraints.NotBlank
interface GenreRepository {
fun findById(id: Long): Publisher<Genre?>
fun save(name: String): Publisher<Genre>
fun saveWithException(@NotBlank name: String): Publisher<Genre>
fun deleteById(id: Long)
fun findAll(args: SortingAndOrderArguments): Publisher<Genre>
fun update(id: Long, @NotBlank name: String): Publisher<Int>
}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:
kapt("io.micronaut.validation:micronaut-validation-processor")
implementation("io.micronaut.validation:micronaut-validation")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
class GenreUpdateCommand(var id: Long, @field:NotBlank var name: String)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:
./gradlew testThen open build/reports/tests/test/index.html in a browser to see the results.
Test 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 ./gradlew 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). |