micronaut-jpa-hibernate-maven-java

Requirements

  • JDK 17+
  • Docker installed to run PostgreSQL.

Project Structure

micronaut.application.name=micronautguide
#tag::application[]
application.max=50
#end::application[]
#tag::datasource[]
datasources.default.password=${JDBC_PASSWORD:""}
datasources.default.url=${JDBC_URL:`jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE`}
datasources.default.username=${JDBC_USER:sa}
datasources.default.driver-class-name=${JDBC_DRIVER:org.h2.Driver}
#end::datasource[]
#tag::jpa[]
jpa.default.properties.hibernate.hbm2ddl.auto=update
jpa.default.properties.hibernate.show_sql=true
#end::jpa[]

Genre.java

...
@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<>();
    
    ...

Book.java

...
@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() {}
    
    ...

Running & Testing local

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

Testing

./mvnw test

Running

./mvnw mn:run

Running prod

export JDBC_URL=jdbc:postgresql://localhost:5432/micronaut
export JDBC_USER=dbuser
export JDBC_PASSWORD=theSecretPassword
export JDBC_DRIVER=org.postgresql.Driver
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

./mvnw mn:run

Source code: https://github.com/ZbCiok/zjc-examples/tree/main/micronaut/micronaut-jpa-hibernate-maven-java

Mark