Video in progress
What does `@Immutable` give you in Hibernate, and for which entities do you use it?
@Immutable makes an entity read-only: Hibernate sends no UPDATE for it, takes it out of dirty checking, and makes it fit the read-only cache strategy. It's good for reference data, views, and audit and event tables, but an attempt to modify it is often silently ignored.
📖 Answer
@Entity
@Immutable
@Table(name = "country")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
class Country {
@Id String code;
String name;
}
What changes:
- a loaded
Countryis read-only: Hibernate doesn't keep its snapshot and doesn't compare it on flush. On screens that load thousands of such entities, this saves memory and flush time; - if you call
country.setName("X")and commit, no UPDATE goes out. There's no error, which is why this can stay hidden in tests; - for an HQL bulk
update Country ..., Hibernate either logs a warning or throws an exception, depending on thehibernate.query.immutable_entity_update_query_handling_modesetting; persist()andremove()work: immutable means "created, then never changed";
If you put it on a collection (@Immutable on a @OneToMany), adding or removing an element of the collection throws an exception.
Where I use it: countries, currency codes, tariff history, append-only tables like an event store or payment_log, and entities that map a database view. It also signals intent at the domain level: whoever reads the code sees right away that this data doesn't change.
If you need to make an entire query read-only (even when the entity itself is mutable), @Immutable is the wrong tool; the org.hibernate.readOnly hint or @Transactional(readOnly = true) is more appropriate.
Sign up to mark studied questions and save your progress.