mn create-app example.micronaut.micronautguide --build=maven --lang=java
Access a database with JPA and Hibernate Reactive
Learn how to use Hibernate Reactive with the Micronaut Framework.
Authors: Tim Yates, Roman Naglic
Micronaut Version: 3.9.2
1. 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.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE
-
JDK 11 or greater installed with
JAVA_HOME
configured appropriately
3. 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
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
If you don’t specify the --build argument, Gradle is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.
|
The previous command creates a Micronaut application with the default package example.micronaut
in a directory named micronautguide
.
4.1. Data Source configuration
Add the following dependencies:
<dependency> (1)
<groupId>io.micronaut.reactor</groupId>
<artifactId>micronaut-reactor</artifactId>
<scope>compile</scope>
</dependency>
<dependency> (2)
<groupId>io.micronaut.sql</groupId>
<artifactId>micronaut-hibernate-reactive</artifactId>
<scope>compile</scope>
</dependency>
<dependency> (3)
<groupId>io.vertx</groupId>
<artifactId>vertx-mysql-client</artifactId>
<scope>compile</scope>
</dependency>
1 | Add a dependency to the Micronaut Framework Project Reactor support |
2 | Configures Hibernate Reactive/JPA beans. |
3 | Adds a dependency to the Vert.x MySQL client. |
4.2. JPA configuration
Add the next snippet to src/main/resources/application.yml
to configure JPA:
jpa:
default:
reactive: true
properties:
hibernate:
connection:
db-type: mysql
hbm2ddl:
auto: create-drop
show_sql: true
4.3. Domain
Create the domain entities:
package example.micronaut.domain;
import io.micronaut.serde.annotation.Serdeable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
import static javax.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 javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import static javax.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 +
'}';
}
}
4.4. 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 a ApplicationConfigurationProperties
class:
package example.micronaut;
import io.micronaut.context.annotation.ConfigurationProperties;
@ConfigurationProperties("application") (1)
public class ApplicationConfigurationProperties implements ApplicationConfiguration {
private final int DEFAULT_MAX = 10;
private int max = DEFAULT_MAX;
@Override
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
}
1 | The @ConfigurationProperties annotation takes the configuration prefix. |
You can override max
if you add to your src/main/resources/application.yml
:
application:
max: 50
4.5. Repository 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 javax.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:
package example.micronaut;
import example.micronaut.domain.Genre;
import jakarta.inject.Singleton;
import org.hibernate.SessionFactory;
import org.hibernate.reactive.stage.Stage;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import javax.persistence.PersistenceException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
@Singleton (1)
public class GenreRepositoryImpl implements GenreRepository {
private static final List<String> VALID_PROPERTY_NAMES = Arrays.asList("id", "name");
private final ApplicationConfiguration applicationConfiguration;
private final Stage.SessionFactory sessionFactory;
public GenreRepositoryImpl(
ApplicationConfiguration applicationConfiguration, (2)
SessionFactory sessionFactory (3)
) {
this.applicationConfiguration = applicationConfiguration;
this.sessionFactory = sessionFactory.unwrap(Stage.SessionFactory.class);
}
@Override
public Publisher<Optional<Genre>> findById(long id) {
return Mono.fromCompletionStage(sessionFactory.withTransaction(session -> (4)
find(session, id)
));
}
CompletionStage<Optional<Genre>> find(Stage.Session session, Long id) {
return session.find(Genre.class, id).thenApply(Optional::ofNullable);
}
@Override
public Publisher<Genre> save(String name) {
return Mono.fromCompletionStage(sessionFactory.withTransaction(session -> {
Genre entity = new Genre(name);
return session.persist(entity).thenApply(v -> entity);
}));
}
@Override
public Publisher<Genre> saveWithException(String name) {
return Mono.fromCompletionStage(sessionFactory.withTransaction(session -> {
Genre entity = new Genre(name);
return session.persist(entity).thenApply(v -> {
throw new PersistenceException();
});
}));
}
@Override
public void deleteById(long id) {
sessionFactory.withTransaction(session -> session.find(Genre.class, id).thenApply(session::remove));
}
@Override
public Publisher<Genre> findAll(SortingAndOrderArguments args) {
String qlString = createQuery(args);
return Mono.fromCompletionStage(sessionFactory.withTransaction(session -> {
Stage.Query<Genre> query = session.createQuery(qlString, Genre.class);
query.setMaxResults(args.getMax().orElseGet(applicationConfiguration::getMax));
args.getOffset().ifPresent(query::setFirstResult);
return query.getResultList();
}))
.flatMapMany(Flux::fromIterable);
}
private String createQuery(SortingAndOrderArguments args) {
String qlString = "SELECT g FROM Genre as g";
if (args.getOrder().isPresent() && args.getSort().isPresent() && VALID_PROPERTY_NAMES.contains(args.getSort().get())) {
qlString += " ORDER BY g." + args.getSort().get() + ' ' + args.getOrder().get().toLowerCase();
}
return qlString;
}
@Override
public Publisher<Integer> update(long id, String name) {
return Mono.fromCompletionStage(sessionFactory.withTransaction(session -> session.createQuery("UPDATE Genre g SET name = :name where id = :id")
.setParameter("name", name)
.setParameter("id", id)
.executeUpdate()));
}
}
1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
2 | Inject the ApplicationConfiguration . |
3 | Inject the Hibernate SessionFactory . |
4 | Grab a transactional session from the SessionFactory to run our query. |
4.6. Controller
Micronaut validation is built on the standard framework – JSR 380, also known as Bean Validation 2.0.
Hibernate Validator is a reference implementation of the validation API. Micronaut has built-in support for validation of beans that are annotated with javax.validation
annotations.
The necessary dependencies are included by default when creating a new application, so you don’t need to add anything else.
Create two classes to encapsulate Save and Update operations:
package example.micronaut;
import io.micronaut.serde.annotation.Serdeable;
import javax.validation.constraints.NotBlank;
@Serdeable (1)
public class GenreSaveCommand {
@NotBlank
private String name;
public GenreSaveCommand(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
package example.micronaut;
import io.micronaut.serde.annotation.Serdeable;
import javax.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:
package example.micronaut;
import io.micronaut.serde.annotation.Serdeable;
import io.micronaut.core.annotation.Nullable;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Positive;
import javax.validation.constraints.PositiveOrZero;
import java.util.Optional;
@Serdeable
public class SortingAndOrderArguments {
@Nullable
@PositiveOrZero (1)
private Integer offset;
@Nullable
@Positive (1)
private Integer max;
@Nullable
@Pattern(regexp = "id|name") (1)
private String sort;
@Nullable
@Pattern(regexp = "asc|ASC|desc|DESC") (1)
private String order;
public SortingAndOrderArguments(@Nullable Integer offset, @Nullable Integer max, @Nullable String sort, @Nullable String order) {
this.offset = offset;
this.max = max;
this.sort = sort;
this.order = order;
}
public Optional<Integer> getOffset() {
return Optional.ofNullable(offset);
}
public void setOffset(@Nullable Integer offset) {
this.offset = offset;
}
public Optional<Integer> getMax() {
return Optional.ofNullable(max);
}
public void setMax(@Nullable Integer max) {
this.max = max;
}
public Optional<String> getSort() {
return Optional.ofNullable(sort);
}
public void setSort(@Nullable String sort) {
this.sort = sort;
}
public Optional<String> getOrder() {
return Optional.ofNullable(order);
}
public void setOrder(@Nullable String order) {
this.order = order;
}
}
1 | Use javax.validation.constraints Constraints to ensure the incoming data matches your expectations. |
Create GenreController
, a controller which exposes a resource with the common CRUD operations:
package example.micronaut;
import example.micronaut.domain.Genre;
import io.micronaut.core.async.annotation.SingleResult;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Delete;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.annotation.Put;
import io.micronaut.http.annotation.Status;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import javax.persistence.PersistenceException;
import javax.validation.Valid;
import java.net.URI;
import static io.micronaut.http.HttpHeaders.LOCATION;
@Controller("/genres") (1)
class GenreController {
private final GenreRepository genreRepository;
GenreController(GenreRepository genreRepository) { (2)
this.genreRepository = genreRepository;
}
@Get("/{id}") (3)
@SingleResult
Publisher<Genre> show(Long id) {
return Mono.from(genreRepository.findById(id))
.flatMap(g -> g.map(Mono::just).orElseGet(Mono::empty)); (4)
}
@Put (5)
Publisher<HttpResponse<?>> update(@Body @Valid GenreUpdateCommand command) { (6)
return Mono.from(genreRepository.update(command.getId(), command.getName()))
.map(i -> HttpResponse
.noContent()
.header(LOCATION, location(command.getId()).getPath())); (7)
}
@Get(value = "/list{?args*}") (8)
Publisher<Genre> list(@Valid SortingAndOrderArguments args) {
return genreRepository.findAll(args);
}
@Post (9)
@SingleResult
Publisher<HttpResponse<Genre>> save(@Body @Valid GenreSaveCommand cmd) {
return Mono.from(genreRepository.save(cmd.getName()))
.map(genre -> HttpResponse
.created(genre)
.headers(headers -> headers.location(location(genre.getId())))
);
}
@Post("/ex") (10)
@SingleResult
Publisher<MutableHttpResponse<Genre>> saveExceptions(@Body @Valid GenreSaveCommand cmd) {
return Mono.from(genreRepository.saveWithException(cmd.getName()))
.map(genre -> HttpResponse
.created(genre)
.headers(headers -> headers.location(location(genre.getId()))))
.onErrorReturn(PersistenceException.class, HttpResponse.noContent());
}
@Delete("/{id}") (11)
@Status(HttpStatus.NO_CONTENT) (12)
<T> HttpResponse<T> delete(Long id) {
genreRepository.deleteById(id);
return HttpResponse.noContent();
}
private URI location(Long id) {
return URI.create("/genres/" + id);
}
}
1 | The class is defined as a controller with the @Controller annotation mapped to the path /genres . |
2 | Use constructor injection to inject a bean of type GenreRepository . |
3 | The @Get annotation maps the show method to an HTTP GET request on /{id} . |
4 | Returning an empty Publisher when the genre doesn’t exist makes the Micronaut framework respond with 404 (not found). |
5 | Maps a PUT request to /genres which attempts to update a genre. |
6 | Add @Valid to any method parameter which requires validation. |
7 | Add custom headers to the response. |
8 | Maps a GET request to /genres which returns a list of genres. |
9 | Maps a POST request to /genres which attempts to save a genre. |
10 | Maps a POST request to /ex which generates an exception. |
11 | The @Delete annotation maps the delete method to an HTTP Delete request on /genres/{id} . |
12 | You can return void in your controller’s method and specify the HTTP status code via the @Status annotation. |
4.7. Writing Tests
Create a test to verify the CRUD operations:
package example.micronaut;
import example.micronaut.domain.Genre;
import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import static io.micronaut.http.HttpHeaders.LOCATION;
import static io.micronaut.http.HttpStatus.BAD_REQUEST;
import static io.micronaut.http.HttpStatus.CREATED;
import static io.micronaut.http.HttpStatus.NOT_FOUND;
import static io.micronaut.http.HttpStatus.NO_CONTENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@MicronautTest (1)
@TestInstance(TestInstance.Lifecycle.PER_CLASS) (2)
class GenreControllerTest {
@Inject
@Client("/")
HttpClient httpClient; (3)
private BlockingHttpClient blockingClient;
@BeforeEach
void setup() {
blockingClient = httpClient.toBlocking();
}
@Test
void supplyAnInvalidOrderTriggersValidationFailure() {
HttpClientResponseException thrown = assertThrows(HttpClientResponseException.class, () ->
blockingClient.exchange(HttpRequest.GET("/genres/list?order=foo"))
);
assertNotNull(thrown.getResponse());
assertEquals(BAD_REQUEST, thrown.getStatus());
}
@Test
void testFindNonExistingGenreReturns404() {
HttpClientResponseException thrown = assertThrows(HttpClientResponseException.class, () ->
blockingClient.exchange(HttpRequest.GET("/genres/99"))
);
assertNotNull(thrown.getResponse());
assertEquals(NOT_FOUND, thrown.getStatus());
}
@Test
void testGenreCrudOperations() {
List<Long> genreIds = new ArrayList<>();
HttpRequest<?> request = HttpRequest.POST("/genres", new GenreSaveCommand("DevOps")); (4)
HttpResponse<?> response = blockingClient.exchange(request);
genreIds.add(entityId(response));
assertEquals(CREATED, response.getStatus());
request = HttpRequest.POST("/genres", new GenreSaveCommand("Microservices")); (4)
response = blockingClient.exchange(request);
assertEquals(CREATED, response.getStatus());
Long id = entityId(response);
genreIds.add(id);
request = HttpRequest.GET("/genres/" + id);
Genre genre = blockingClient.retrieve(request, Genre.class); (5)
assertEquals("Microservices", genre.getName());
request = HttpRequest.PUT("/genres", new GenreUpdateCommand(id, "Micro-services"));
response = blockingClient.exchange(request); (6)
assertEquals(NO_CONTENT, response.getStatus());
request = HttpRequest.GET("/genres/" + id);
genre = blockingClient.retrieve(request, Genre.class);
assertEquals("Micro-services", genre.getName());
request = HttpRequest.GET("/genres/list");
List<Genre> genres = blockingClient.retrieve(request, Argument.of(List.class, Genre.class));
assertEquals(2, genres.size());
request = HttpRequest.POST("/genres/ex", new GenreSaveCommand("Microservices")); (4)
response = blockingClient.exchange(request);
assertEquals(NO_CONTENT, response.getStatus());
request = HttpRequest.GET("/genres/list");
genres = blockingClient.retrieve(request, Argument.of(List.class, Genre.class));
assertEquals(2, genres.size());
request = HttpRequest.GET("/genres/list?max=1");
genres = blockingClient.retrieve(request, Argument.of(List.class, Genre.class));
assertEquals(1, genres.size());
assertEquals("DevOps", genres.get(0).getName());
request = HttpRequest.GET("/genres/list?max=1&order=desc&sort=name");
genres = blockingClient.retrieve(request, Argument.of(List.class, Genre.class));
assertEquals(1, genres.size());
assertEquals("Micro-services", genres.get(0).getName());
request = HttpRequest.GET("/genres/list?max=1&offset=10");
genres = blockingClient.retrieve(request, Argument.of(List.class, Genre.class));
assertEquals(0, genres.size());
// cleanup:
for (Long genreId : genreIds) {
request = HttpRequest.DELETE("/genres/" + genreId);
response = blockingClient.exchange(request);
assertEquals(NO_CONTENT, response.getStatus());
}
}
private Long entityId(HttpResponse response) {
String path = "/genres/";
String value = response.header(LOCATION);
if (value == null) {
return null;
}
int index = value.indexOf(path);
if (index != -1) {
return Long.valueOf(value.substring(index + path.length()));
}
return null;
}
}
1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
2 | Classes that implement TestPropertyProvider must use this annotation to create a single class instance for all tests (not necessary in Spock tests). |
3 | Inject the HttpClient bean and point it to the embedded server. |
4 | Creating HTTP Requests is easy thanks to the Micronaut framework fluid API. |
5 | If you care just about the object in the response use retrieve . |
6 | Sometimes, receiving just the object is not enough and you need information about the response. In this case, instead of retrieve you should use the exchange method. |
5. Testing the Application
To run the tests:
./mvnw test
6. Test Resources
When the application is started locally — either under test or by running the application — 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.
7. 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=theSecretPassword
Run the application. If you look at the output you can see that the application uses MySQL:
8. 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" }'
9. Next steps
Read more about Configurations for Data Access section in the Micronaut documentation.
10. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.