A Java Record is not suitable to be used as a JPA or Hibernate entity.
Using Java Records as DTOs
Let’s assume we have the following PostInfo and AuditInfo DTO classes:
With Java Records, we can define the AuditInfo like this:
public record AuditInfo(
and the PostInfo looks as follows:
public record PostInfo(
Now, to use the simple class name instead of the fully-qualified one in JPQL queries, we are going to register the AuditInfo and PostInfo Java Records using the ClassImportIntegrator provided by the Hibernate Types project:
For more details about the ClassImportIntegrator utility, check out this article.
Using Java Records in JPA constructor expression queries
To fetch an AuditInfo DTO projection for a given Post, we can use the following JPQL query:
AuditInfo auditInfo = entityManager.createQuery("""
new AuditInfo (
from Post p
where p.id = :postId
While you can also fetch the AuditInfo using as @SqlResultSetMapping, neither the JPQL constructor Expression nor the @SqlResultSetMapping allows you to fetch the PostInfo as you need to pass a properly instantiated AuditInfo reference in the PostInfo constructor.
Using Java Records using the Hibernate ResultTransformer