Using Java records with JPA for immutable entities
Java records are concise, immutable data carriers, but JPA entities also need database identity, lifecycle state and proxy behaviour. A record is final and normally has a canonical constructor rather than a no-argument constructor, so annotating it with @Entity creates a portability boundary that must be handled deliberately.
The safest design separates immutable domain values from persistence mechanics. Records work well where values never change, while provider-specific annotations, generated keys and change tracking stay at the JPA boundary.
The examples use Java 17, Spring Boot 3, Hibernate 6 and PostgreSQL. They suit payment, ordering and identity services built by teams in Sydney and Melbourne. The site's practical JPA guide offers useful background on the surrounding DTO and persistence choices.
Why records clash with portable entity rules
Jakarta Persistence expects an entity class to be non-final and to provide a public or protected no-argument constructor. A record violates both rules, so @Entity on a record is not portable JPA usage. Hibernate can support direct mappings under its own rules, but that distinction should appear in project documentation.
Generated equals and hashCode also compare every component, while JPA normally compares entities by identifier. Generated toString can expose emails or other personal details in logs, making equality and diagnostic output explicit design decisions.
A portable record and entity boundary
Keep the business value immutable while giving JPA a conventional persistence class:
public record Customer(UUID id, String email, String displayName) {}
@Entity
@Table(name = "customers")
public class CustomerEntity {
@Id
private UUID id;
private String email;
private String displayName;
protected CustomerEntity() {
}
CustomerEntity(Customer source) {
this.id = source.id();
this.email = source.email();
this.displayName = source.displayName();
}
Customer toRecord() {
return new Customer(id, email, displayName);
}
}
The entity is an adapter, not an object for callers to mutate. Repositories convert it to Customer, and application code receives the record. This provider-neutral pattern leaves generated values, dirty checking and change tracking under the ORM's control.
Direct Hibernate mappings and safety checks
Where Hibernate-specific behaviour is acceptable, recent Hibernate 6 releases can map a record directly and mark it read-only:
@Immutable
@Entity
@Table(name = "customer_snapshots")
public record CustomerSnapshot(
@Id
@Column(name = "customer_id")
UUID id,
@Column(name = "email", nullable = false)
String email,
@Column(name = "display_name", nullable = false)
String displayName
) {
}
This is provider functionality rather than portable Jakarta Persistence. Treat the record as insert-and-read data: lazy associations, dirty checking and in-place version changes do not suit an immutable object.
A direct mapping should satisfy these constraints:
- Assign a UUID or ULID in the application to avoid generated-key timing.
- Keep components simple and avoid lazy relationships or proxies.
- Choose insert-only semantics before exposing write operations.
- Override equality when identifier-based JPA identity matters.
- Replace sensitive generated
toStringoutput.
The test suite should verify these behaviours:
- Test persistence, clearing, retrieval and transaction rollback.
- Confirm attempted updates follow the documented policy.
- Check schema validation against the target database.
- Avoid proxy-dependent operations on final record classes.
- Pin Hibernate and Spring Boot versions in tests.
Identifiers and update strategies
Generated identifiers are awkward for immutable records because a value produced after construction cannot flow back into the object. An application-generated UUID or ULID avoids that timing issue. Align the identifier's Java type with its database representation, especially when using PostgreSQL.
When business facts change, do not expect dirty checking to rewrite the record. Store a new snapshot or revision, use append-only rows, or move mutable lifecycle fields such as status into a conventional entity. Each option gives updates an explicit history.
Spring Data projections as immutable records
Records are particularly safe as query results because they never become managed entities. A Spring Data repository can construct them directly in JPQL:
public record CustomerSummary(UUID id, String email) {}
interface CustomerRepository extends Repository<CustomerEntity, UUID> {
@Query("select new com.example.shop.CustomerSummary(c.id, c.email) " +
"from CustomerEntity c")
List<CustomerSummary> findSummaries();
}
Constructor expressions avoid a separate hydration step and keep database columns separate from the public contract. Bean Validation can reject malformed results at the boundary. Command methods should return domain records rather than exposing managed persistence objects.
Transactions, auditing and event models
An immutable mapped row still follows normal transaction semantics: persist, flush, commit and rollback remain meaningful. Database defaults are often cleaner than mutable auditing fields on a record, while Flyway should own schema changes so deployment order stays controlled.
Records also suit domain events such as CustomerRegistered, but an event is not automatically durable. If another service must consume it, write it to an outbox and publish after commit. The outbox status changes, so use a mutable adapter around the immutable payload.
Australian production considerations
Sydney and Melbourne are major Australian hubs for commerce and fintech systems. Store AUD amounts as BigDecimal, never floating point, and remember that consumer prices usually include the 10% GST. Snapshots preserve the amount displayed when tax rules or promotions later change.
Personal data is governed by the Privacy Act 1988 and Australian Privacy Principles, including APP 8 on disclosure and APP 11 on security. Serious breaches may trigger the Notifiable Data Breaches scheme. Immutability reduces accidental edits but does not replace encryption, access controls or retention rules.
The Privacy Act is not a blanket data-localisation law, yet Australian contracts may favour AWS regions in Sydney or Melbourne. Operational plans should also account for the time spread from Perth to Brisbane and daylight-saving changes. In this setting, records work best as stable snapshots and query models, with persistence adapters handling identity and lifecycle duties.