Reverse-engineering the database schema

Let's say you have a database schema to manage books and authors. A possible SQL query for such a database could look like the following:

SELECT AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME
FROM AUTHOR
ORDER BY AUTHOR.LAST_NAME ASC

jOOQ allows you to write this same SQL query, but in Java:

dslContext.select(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
      .from(AUTHOR)
      .orderBy(AUTHOR.LAST_NAME.asc()

As you can see, the syntax is quite close to actual SQL. You might be wondering where the AUTHOR object and its properties come from. They come from code generated by jOOQ. The code generation process can be automated with Maven. The following code shows how to configure the jooq-codegen-maven plugin in your pom.xml:

<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<version>3.9.5</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<jdbc>
<url>${datasource.url}</url>
<user>${datasource.username}</user>
<password>${datasource.password}</password>
</jdbc>
<generator>
<database>
<name>org.jooq.util.h2.H2Database</name>
</database>
<target>
<packageName>packt.vaadin.datacentric.chapter06.jooq
</packageName>
<directory>target/generated-sources/jooq</directory>
</target>
</generator>
</configuration>
</plugin>

You have to configure the connection properties so that the generator can scan the database schema. You also have to configure the database to use it (H2, in this example). Finally, you have to configure the package to be used for the generated code and the directory inside your project where this package is going to reside.

There's one small detail, though. We are using expressions (such as ${datasource.url}) to specify the database connection properties. How can you use values coming from a .properties file inside the pom.xml file? By using the properties-maven-plugin Maven plugin:

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>

<file>
src/main/resources/datasource.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>

With the previous configuration, Maven will be able to read the properties in the datasource.properties file and replace the corresponding expressions in the pom.xml file.

After configuring this two Maven plugins, you can run mvn clean package to reverse-engineer the database schema and generate the corresponding code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset