Skip to content
Advertisement

Using Java records as JPA embeddables

I want to use Java records as embeddable objects with JPA. For example I want to wrap the ID in a record to make it typesafe:

JavaScript

But If I try to persist it with Hibernate 5.4.32 I get the following error:

JavaScript

So it looks like Hibernate would treat the record Id like an entity, although it is an @Embeddable.

The same happens with non-id fields and @Embedded:

JavaScript

Is there a way to use @Embeddable records with JPA/Hibernate?

Advertisement

Answer

Java records with a single field can be used for custom ID types or any other value object with AttributeConverters.

In the entity class the ID type is used with @Id as usual:

JavaScript

Note that the record Id doesn’t have any annotation.

The converter makes it possible to use records:

JavaScript

Don’t forget to set autoApply = true to have this converter applied automatically (without referencing it explicitly on the respective field).

Records with more than one field could be mapped with a Hibernate UserType, but that is a bit cumbersome.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement