Saturday, 2 April 2016

Type safe queries in Java with Query DSL

When writing applications you will at some need to write to a database. In the java world, you can do it directly with JDBC, JDBI or Spring JdbcTemplate or you can use a full blown orm like hibernate.  Query DSL (SQL version) is a middle ground not orm and not pure JDBC. Below is how to set it up.

Add the following dependencies to your pom:

Add the following plugin to the build section:
          <!-- Driver to use to connect to the db -->
          <!-- Database connection url -->
          <!-- Database user -->
          <!-- Database password -->
          <!-- Tell query dsl that generated classes should be under this package -->
          <!-- Source where to put the generated classes -->
          <!-- database driver dependencies -->

Now running mvn test will generate your classes to query the database.

Now querying becomes very easy and type safe for example to select columns from message table you would do:, message.ref, message.body)

No comments:

Post a Comment