Search code examples
jooq

JOOQ howto generate additional Pojos for projections


I have a DTO that I use for projections in my queries, which is based on a POJO created by JOOQ but adds a custom field (retrieved from a join).

Currently, I need to:

  • Define the DTO for projection, inherit from the generated POJO
  • add the custom field in the DTO
  • create the constructor

It is a tiny class, but needs to be amended each time I modify the underlying POJO.

I wonder if this process can be automated? Can I tap into the generation process to emit my DTO as well?


Solution

  • I can see several ways of doing this:

    1. Subclass the generated POJO. This leaves the POJO class untouched and allows for adding stuff only when you need it. This also works with immutable POJOs
    2. Generate custom code using a "custom code section". This will make sure your custom code will get re-generated every time you generate jOOQ code. This will now work with immutable POJOs, because you cannot change the constructor.
    3. Use a view. Views are SQL's most underused and underrated feature. Using a view, you'd automatically get the enhanced POJO from your code generator, and you will never have to think about the join again.