Search code examples
micronautmicronaut-data

Is there a way to export the DDL to a file with Micronaut Data JDBC?


Let‘s say I have implemented Micronaut Data JDBC entity such as


@MappedEntity
record Book(
        @Id @GeneratedValue @Nullable Long id, 
        @DateCreated @Nullable Date dateCreated,
        String title,
        int pages) {
}

and I would like generate the DDL representing my entities. Using the «ORM» approach, my development workflow is usually

  1. Design entities
  2. Export DDL to a file or console and verify my SQL expectations with the actual output (when unhappy goto 1)
  3. Use DDL as a Flyway migration script
  4. Configure Hibernate to verify the DDL on startup, to make sure the DB is in sync with the entity model.

For 2), in the Hibernate world I simply use SchemaExport and this creates the dialect specific DDL such as this listing for MariaDB/MySQL below.

CREATE TABLE book (
     id UUID NOT NULL,
     date_created DATE,
     title VARCHAR(255) NOT NULL,
     pages INT NOT NULL,
     PRIMARY KEY(id)
) ENGINE=InnoDB;

So I got two questions here:

  1. Is there a way to achieve the same thing using Micronaut Data JPA and export the DDL to a file or console?
  2. Is there a way to validate the actual database schema on startup, to make sure the entities are in sync with the underlying database schema?

Solution

  • Micronaut Data JDBC comes with just a basic schema generator, you cannot enable the file export, but you can enable the query logging:

    <logger name="io.micronaut.data.query" level="trace" />
    

    And schema creation for your data source with schema-generate property:

    datasources:
      default:
        url: jdbc:h2:mem:devDb
        driverClassName: org.h2.Driver
        username: sa
        password: ''
        schema-generate: CREATE_DROP
        dialect: H2