In the past implementation, we had to start a Postgres server, supply a script to initialize the tables in database, and had to connect to the database to generate jOOQ code. The flow is not ideal because it creates a dependency to the database. One of the solutions is to generate the jooQ code from a different container. I use two tools to solve this: Testcontainers and Flyway.
Testcontainers is a framework to create a throwaway instance of Docker container, and Flyway is a library to migrate database. We will create a Postgres container using Testcontainers and Flyway to initialize the tables needed. jooQ will then generate the code from the Testcontainers instance. We don’t have to supply our database credentials during build process anymore if using this method, thus removing the dependency to the Postgres server.
In the code snippet above, the plugin does two things:
In generate-sources phase, the plugin starts a new PostgreSQL container with the image tag postgres:15-alpine. It also creates a database named postgres, with username and password provided by the project. At the end of the script, it sets several project properties: db.url, testcontainer.containerid, and testcontainer.imageName.
During test phase, the project stops the instance and remove the container.
The plugin depends on org.testcontainers:postgresql package to run.
To execute SQL script, we use flyway-maven-plugin plugin:
This plugin uses db.url,db,username, and db.password properties as a part of the configuration. The SQL scripts are stored in src/man/resources/db/migration. I named my script file V1_0__init_tables.sql to fulfill Flyway’s naming convention.
There is a library that can do all the above processes: testcontainers-jooq-codegen-maven-plugin. It can create a DB server using a Testcontainer instance, run Flyway migration script, and generate the jooQ code. We can remove the dependencies to groovy-maven-plugin, flyway-maven-plugin, and jooq-codegen-maven if we use this library.
This plugin needs dependency to Testcontainer’s Postgres library and Postgres JDBC driver. Under database section, set the type to POSTGRES because we use Postgres database and postgres:15-alpine as the container image for mimicking the existing environment. For Flyway configuration, set the directory to src/main/resources/db/migration. For jooQ section, set the target package name to com.tabunganku.jooq.model and the target directory target/generated-sources/jooq. Run mvn clean install to generate the jOOQ code and build the project.
I prefer testcontainers-jooq-codegen-maven-plugin because it allows me to integrate quicker and without any hassle. Using multiple libraries enables a lot of customization, but the project does not require it at the moment.