Access a database with JPA and Hibernate

Learn how to access a database with JPA and Hibernate using the Micronaut framework.

Authors: Iván López, Sergio del Amo

Micronaut Version: 3.5.2

1. Getting Started

In this guide, we will create a Micronaut application written in Groovy.

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 1.8 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.

4. 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=groovy
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:

pom.xml
<dependency> (1)
    <groupId>io.micronaut.sql</groupId>
    <artifactId>micronaut-hibernate-jpa</artifactId>
    <scope>compile</scope>
</dependency>
<dependency> (2)
    <groupId>io.micronaut.sql</groupId>
    <artifactId>micronaut-jdbc-hikari</artifactId>
    <scope>compile</scope>
</dependency>
<dependency> (3)
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency> (4)
    <groupId>jakarta.persistence</groupId>
    <artifactId>jakarta.persistence-api</artifactId>
    <version>2.2.3</version>
    <scope>compile</scope>
</dependency>
1 Configures Hibernate/JPA EntityManagerFactory beans.
2 Configures SQL DataSource instances using Hikari Connection Pool.
3 Add dependency to in-memory H2 Database.
4 Add dependency to Jakarta Persistence API.

Define the data source in src/main/resources/application.yml.

src/main/resources/application.yml
datasources:
  default:
    url: ${JDBC_URL:`jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE`}
    username: ${JDBC_USER:sa}
    password: ${JDBC_PASSWORD:""}
    driverClassName: ${JDBC_DRIVER:org.h2.Driver}
This way of defining the datasource properties means that we can externalize the configuration, for example for production environment, and also provide a default value for development. If the environment variables are not defined the Micronaut framework will use the default values.
Also keep in mind that it is necessary to escape the : in the connection URL using backticks `.

4.2. JPA configuration

Add the next snippet to src/main/resources/application.yml to configure JPA:

src/main/resources/application.yml
jpa:
  default:
    properties:
      hibernate:
        hbm2ddl:
          auto: update
        show_sql: true

4.3. Domain

Create the domain entities:

src/main/groovy/example/micronaut/domain/Genre.groovy
package example.micronaut.domain

import com.fasterxml.jackson.annotation.JsonIgnore
import groovy.transform.CompileStatic

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 static javax.persistence.GenerationType.AUTO

@CompileStatic
@Entity
@Table(name = 'genre')
class Genre {

    @Id
    @GeneratedValue(strategy = AUTO)
    Long id

    @NotNull
    @Column(name = 'name', nullable = false, unique = true)
    String name

    @JsonIgnore
    @OneToMany(mappedBy = 'genre')
    Set<Book> books = []

    Genre() {}

    Genre(@NotNull String name) {
        this.name = name
    }

    @Override
    String toString() {
        "Genre{id=$id, name='$name'}"
    }
}

The previous domain has a OneToMany relationship with the domain Book.

src/main/groovy/example/micronaut/domain/Book.groovy
package example.micronaut.domain

import groovy.transform.CompileStatic

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

@CompileStatic
@Entity
@Table(name = 'book')
class Book {

    @Id
    @GeneratedValue(strategy = AUTO)
    Long id

    @NotNull
    @Column(name = 'name', nullable = false)
    String name

    @NotNull
    @Column(name = 'isbn', nullable = false)
    String isbn

    @ManyToOne
    Genre genre

    Book() {}

    Book(@NotNull String isbn,
         @NotNull String name,
         Genre genre) {
        this.isbn = isbn
        this.name = name
        this.genre = genre
    }

    @Override
    String toString() {
        "Book{id=$id, name='$name', isbn='$isbn', genre=$genre}"
    }
}

4.4. Application Configuration

Create an interface to encapsulate the application configuration settings:

src/main/groovy/example/micronaut/ApplicationConfiguration.groovy
package example.micronaut

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:

src/main/groovy/example/micronaut/ApplicationConfigurationProperties.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.context.annotation.ConfigurationProperties

@CompileStatic
@ConfigurationProperties('application') (1)
class ApplicationConfigurationProperties implements ApplicationConfiguration {

    private final int DEFAULT_MAX = 10

    int max = DEFAULT_MAX
}
1 The @ConfigurationProperties annotation takes the configuration prefix.

You can override max if you add to your src/main/resources/application.yml:

src/main/resources/application.yml
application:
  max: 50

4.5. Repository Access

To mark the transaction demarcations, we use the Java EE 7 javax.transaction.Transactional annotation.

To use it, you have to include the micronaut-data-processor dependency in your annotation processor configuration:

pom.xml
<dependency>
    <groupId>io.micronaut.data</groupId>
    <artifactId>micronaut-data-hibernate-jpa</artifactId>
    <scope>compile</scope>
</dependency>

Next, create a repository interface to define the operations to access the database:

src/main/groovy/example/micronaut/GenreRepository.groovy
package example.micronaut

import example.micronaut.domain.Genre

import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull

interface GenreRepository {

    Optional<Genre> findById(long id)

    Genre save(@NotBlank String name)

    Genre saveWithException(@NotBlank String name)

    void deleteById(long id)

    List<Genre> findAll(@NotNull SortingAndOrderArguments args)

    int update(long id, @NotBlank String name)
}

The implementation:

src/main/groovy/example/micronaut/GenreRepositoryImpl.groovy
package example.micronaut

import example.micronaut.domain.Genre
import io.micronaut.transaction.annotation.ReadOnly
import jakarta.inject.Singleton

import javax.persistence.EntityManager
import javax.persistence.PersistenceException
import javax.persistence.TypedQuery
import javax.transaction.Transactional
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull

@Singleton (1)
class GenreRepositoryImpl implements GenreRepository {

    private static final List<String> VALID_PROPERTY_NAMES = ['id', 'name']

    private final EntityManager entityManager  (2)
    private final ApplicationConfiguration applicationConfiguration

    GenreRepositoryImpl(EntityManager entityManager,
                        ApplicationConfiguration applicationConfiguration) { (2)
        this.entityManager = entityManager
        this.applicationConfiguration = applicationConfiguration
    }

    @Override
    @ReadOnly  (3)
    Optional<Genre> findById(long id) {
        Optional.ofNullable(entityManager.find(Genre, id))
    }

    @Override
    @Transactional (4)
    Genre save(@NotBlank String name) {
        Genre genre = new Genre(name)
        entityManager.persist(genre)
        genre
    }

    @Override
    @Transactional (4)
    void deleteById(long id) {
        findById(id).ifPresent(entityManager::remove)
    }

    @ReadOnly (3)
    List<Genre> findAll(@NotNull SortingAndOrderArguments args) {
        String qlString = 'SELECT g FROM Genre as g'
        if (args.order.present && args.sort.present && VALID_PROPERTY_NAMES.contains(args.sort.get())) {
            qlString += ' ORDER BY g.' + args.sort.get() + ' ' + args.order.get().toLowerCase()
        }
        TypedQuery<Genre> query = entityManager.createQuery(qlString, Genre)
        query.maxResults = args.max.orElseGet(applicationConfiguration::getMax)
        args.offset.ifPresent(query::setFirstResult)

        query.resultList
    }

    @Override
    @Transactional (4)
    int update(long id, @NotBlank String name) {
        entityManager.createQuery('UPDATE Genre g SET name = :name where id = :id')
                .setParameter('name', name)
                .setParameter('id', id)
                .executeUpdate()
    }

    @Override (4)
    @Transactional (4)
    Genre saveWithException(@NotBlank String name) {
        save(name)
        throw new PersistenceException()
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Easily inject an EntityManager.
3 All database access needs to be wrapped inside a transaction. As the method only reads data from the database, annotate it with @ReadOnly.
4 This method modifies the database, thus it is annotated with @Transactional.

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:

src/main/groovy/example/micronaut/GenreSaveCommand.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.core.annotation.Introspected

import javax.validation.constraints.NotBlank

@CompileStatic
@Introspected (1)
class GenreSaveCommand {

    @NotBlank
    String name

    GenreSaveCommand(String name) {
        this.name = name
    }
}
1 Annotate the class with @Introspected to generate BeanIntrospection metadata at compilation time. This information can be used, for example, to the render the POJO as JSON using Jackson without using reflection.
src/main/groovy/example/micronaut/GenreUpdateCommand.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.core.annotation.Introspected

import javax.validation.constraints.NotBlank

@CompileStatic
@Introspected
class GenreUpdateCommand {

    long id

    @NotBlank
    String name

    GenreUpdateCommand(long id, String name) {
        this.id = id
        this.name = name
    }
}

Create a POJO to encapsulate Sorting and Pagination:

src/main/groovy/example/micronaut/SortingAndOrderArguments.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.core.annotation.Introspected
import io.micronaut.core.annotation.Nullable

import javax.validation.constraints.Pattern
import javax.validation.constraints.Positive
import javax.validation.constraints.PositiveOrZero

@CompileStatic
@Introspected
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

    Optional<Integer> getOffset() {
        Optional.ofNullable(offset)
    }

    void setOffset(@Nullable Integer offset) {
        this.offset = offset
    }

    Optional<Integer> getMax() {
        Optional.ofNullable(max)
    }

    void setMax(@Nullable Integer max) {
        this.max = max
    }

    Optional<String> getSort() {
        Optional.ofNullable(sort)
    }

    void setSort(@Nullable String sort) {
        this.sort = sort
    }

    Optional<String> getOrder() {
        Optional.ofNullable(order)
    }

    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:

src/main/groovy/example/micronaut/GenreController.groovy
package example.micronaut

import example.micronaut.domain.Genre
import groovy.transform.CompileStatic
import io.micronaut.http.HttpResponse
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.scheduling.TaskExecutors
import io.micronaut.scheduling.annotation.ExecuteOn

import javax.persistence.PersistenceException
import javax.validation.Valid

import static io.micronaut.http.HttpHeaders.LOCATION

@CompileStatic
@ExecuteOn(TaskExecutors.IO)  (1)
@Controller('/genres')  (2)
class GenreController {

    private final GenreRepository genreRepository

    GenreController(GenreRepository genreRepository) { (3)
        this.genreRepository = genreRepository
    }

    @Get('/{id}') (4)
    Genre show(Long id) {
        genreRepository
                .findById(id)
                .orElse(null) (5)
    }

    @Put (6)
    HttpResponse<?> update(@Body @Valid GenreUpdateCommand command) { (7)
        int numberOfEntitiesUpdated = genreRepository.update(command.id, command.name)

        HttpResponse
                .noContent()
                .header(LOCATION, location(command.id).path) (8)
    }

    @Get(value = '/list{?args*}') (9)
    List<Genre> list(@Valid SortingAndOrderArguments args) {
        genreRepository.findAll(args)
    }

    @Post (10)
    HttpResponse<Genre> save(@Body @Valid GenreSaveCommand cmd) {
        Genre genre = genreRepository.save(cmd.name)

        HttpResponse
                .created(genre)
                .headers(headers -> headers.location(location(genre.id)))
    }

    @Post('/ex') (11)
    HttpResponse<Genre> saveExceptions(@Body @Valid GenreSaveCommand cmd) {
        try {
            Genre genre = genreRepository.saveWithException(cmd.name)
            HttpResponse
                    .created(genre)
                    .headers(headers -> headers.location(location(genre.id)))
        } catch(PersistenceException ignored) {
            HttpResponse.noContent()
        }
    }

    @Delete('/{id}') (12)
    HttpResponse<?> delete(Long id) {
        genreRepository.deleteById(id)
        HttpResponse.noContent()
    }

    private URI location(Long id) {
        URI.create('/genres/' + id)
    }
}
1 It is critical that any blocking I/O operations (such as fetching the data from the database) are offloaded to a separate thread pool that does not block the Event loop.
2 The class is defined as a controller with the @Controller annotation mapped to the path /genres.
3 Constructor injection.
4 Maps a GET request to /genres/{id} which attempts to show a genre. This illustrates the use of a URL path variable.
5 Returning null when the genre doesn’t exist makes the Micronaut framework respond with 404 (not found).
6 Maps a PUT request to /genres which attempts to update a genre.
7 Add @Valid to any method parameter which requires validation. Use a POJO supplied as a JSON payload in the request to populate command.
8 It is easy to add custom headers to the response.
9 Maps a GET request to /genres which returns a list of genres. This mapping illustrates URL parameters being mapped to a single POJO.
10 Maps a POST request to /genres which attempts to save a genre.
11 Maps a POST request to /ex which generates an exception.
12 Maps a DELETE request to /genres/{id} which attempts to remove a genre. This illustrates the use of a URL path variable.

4.7. Writing Tests

Create a test to verify the CRUD operations:

src/test/groovy/example/micronaut/GenreControllerSpec.groovy
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.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification

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

@MicronautTest (1)
class GenreControllerSpec extends Specification {

    private BlockingHttpClient blockingClient

    @Inject
    @Client('/')
    HttpClient client (2)

    void setup() {
        blockingClient = client.toBlocking()
    }

    void supplyAnInvalidOrderTriggersValidationFailure() {

        when:
        blockingClient.exchange(HttpRequest.GET('/genres/list?order=foo'))

        then:
        HttpClientResponseException e = thrown()
        e.response
        BAD_REQUEST == e.status
    }

    void testFindNonExistingGenreReturns404() {
        when:
        blockingClient.exchange(HttpRequest.GET('/genres/99'))

        then:
        HttpClientResponseException e = thrown()
        e.response
        NOT_FOUND == e.status
    }

    void testGenreCrudOperations() {

        given:
        List<Long> genreIds = []

        when:
        HttpRequest<?> request = HttpRequest.POST('/genres', new GenreSaveCommand('DevOps')) (3)
        HttpResponse<?> response = blockingClient.exchange(request)
        genreIds << entityId(response)

        then:
        CREATED == response.status

        when:
        request = HttpRequest.POST('/genres', new GenreSaveCommand('Microservices')) (3)
        response = blockingClient.exchange(request)

        then:
        CREATED == response.status

        when:
        Long id = entityId(response)
        genreIds << id
        request = HttpRequest.GET('/genres/' + id)

        Genre genre = blockingClient.retrieve(request, Genre) (4)

        then:
        'Microservices' == genre.name

        when:
        request = HttpRequest.PUT('/genres', new GenreUpdateCommand(id, 'Micro-services'))
        response = blockingClient.exchange(request)  (5)

        then:
        NO_CONTENT == response.status

        when:
        request = HttpRequest.GET('/genres/' + id)
        genre = blockingClient.retrieve(request, Genre)


        then:
        'Micro-services' == genre.name

        when:
        request = HttpRequest.GET('/genres/list')
        List<Genre> genres = blockingClient.retrieve(request, Argument.of(List, Genre))

        then:
        2 == genres.size()

        when:
        request = HttpRequest.POST('/genres/ex', new GenreSaveCommand('Microservices')) (3)
        response = blockingClient.exchange(request)

        then:
        NO_CONTENT == response.status

        when:
        request = HttpRequest.GET('/genres/list')
        genres = blockingClient.retrieve(request, Argument.of(List, Genre))

        then:
        2 == genres.size()

        when:
        request = HttpRequest.GET('/genres/list?max=1')
        genres = blockingClient.retrieve(request, Argument.of(List, Genre))

        then:
        1 == genres.size()
        'DevOps' == genres[0].name

        when:
        request = HttpRequest.GET('/genres/list?max=1&order=desc&sort=name')
        genres = blockingClient.retrieve(request, Argument.of(List, Genre))

        then:
        1 == genres.size()
        'Micro-services' == genres[0].name

        when:
        request = HttpRequest.GET('/genres/list?max=1&offset=10')
        genres = blockingClient.retrieve(request, Argument.of(List, Genre))

        then:
        0 == genres.size()

        cleanup:
        for (Long genreId : genreIds) {
            request = HttpRequest.DELETE('/genres/' + genreId)
            response = blockingClient.exchange(request)
            assert NO_CONTENT == response.status
        }
    }

    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 value.substring(index + path.length()) as long
        }

        null
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.
3 Creating HTTP Requests is easy thanks to the Micronaut framework fluid API.
4 If you care just about the object in the response use retrieve.
5 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. Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

7. Using PostgreSQL

When running on production you want to use a real database instead of using H2. Let’s explain how to use PostgreSQL.

After installing Docker, execute the following command to run a PostgreSQL container:

docker run -it --rm \
    -p 5432:5432 \
    -e POSTGRES_USER=dbuser \
    -e POSTGRES_PASSWORD=theSecretPassword \
    -e POSTGRES_DB=micronaut \
    postgres:11.5-alpine

Add PostgreSQL driver dependency:

pom.xml
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

To use PostgreSQL, set up several environment variables which match those defined in application.yml:

export JDBC_URL=jdbc:postgresql://localhost:5432/micronaut
export JDBC_USER=dbuser
export JDBC_PASSWORD=theSecretPassword
export JDBC_DRIVER=org.postgresql.Driver

Run the application again. If you look at the output you can see that the application uses PostgreSQL:

..
...
08:40:02.746 [main] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
....

Connect to your PostgreSQL database, and you will see both genre and book tables.

datagrip

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" }'

8. Next steps

Read more about Configurations for Data Access section in the Micronaut documentation.

9. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.