Video in progress
A record is convenient as a DTO, so why doesn't it work for a JPA entity?
An entity needs a no-args constructor, mutable fields and a subclass for lazy proxies. A record has none of these: the class is final, the fields are final, and there's no no-args constructor.
📖 Answer
What Hibernate does with an entity:
- when reading from the DB, it creates the object with the no-args constructor and then fills in the fields;
- for dirty checking, it changes and compares field values;
- for a lazy
@ManyToOne, it creates a subclass of the entity (a proxy).
None of this works with a record: the class is final, the fields are final, and the only constructor is the canonical one.
But around persistence, records are very handy:
// JPQL projection
record OrderView(Long id, String number, BigDecimal total) {}
@Query("select new com.shop.OrderView(o.id, o.number, o.total) from Order o")
List<OrderView> findViews();
// a record projection works instead of a Spring Data interface too
List<OrderView> findByStatus(Status s);
In Hibernate 6 you can also make a record an @Embeddable (through an instantiator).
Jackson 2.12+ serializes records on its own and reads them through the canonical constructor, so @JsonCreator isn't needed. For validation, if you put @NotNull on the components, Bean Validation checks them through the constructor parameters and the accessors.
In short: an entity is a mutable class, and API and query results are records.
Sign up to mark studied questions and save your progress.