The new Java version 16 includes a new feature: Records
https://openjdk.java.net/jeps/395 “Enhance the Java programming language with records, which are classes that act as transparent carriers for immutable data. Records can be thought of as nominal tuples.”
Let’s try Java records with JPA and jOOQ.
JPA Constructor Expression
One way to use projection in JPA queries is using the constructor expression. The name constructor expression implies that the constructor is called with the fields from the projection.
In the example we have a DTO called EmployeeDTO and the constructor takes two Strings as parameters.
With Java before Java 16 we would create a class like this:
Thanks to Java 16 Records this is now much simpler:
This Record will contain the required constructor and also the methods to get the employeeName and the departmentName so it’s a perfect fit for JPAs constructor expression!
jOOQ SQL Projection
Beside JPA there is another great solution for accessing relational database systems: jOOQ
With jOOQ we can write type-safe SQL in Java. And very often we also want DTOs as a result. Also here Java Records shine:
Java Records are a great addition to the Java language and a great fit to use with persistence technologies like JPA or jOOQ.
If you want to try it on your own, please find the example code on GitHub: https://github.com/72services/java16-jpa-jooq