What is the difference between @Immutable and @Entity(mutable=false) when using Hibernate

24,652

Solution 1

For entity there's practically no difference. @Immutable gets priority (that is if you have entity that's annotated both as @Immutable and @Entity(mutable = "true") it is going to be treated as immutable).

@Immutable can also be used on collections with pretty much the same semantics. Details are here

Solution 2

The org.hibernate.annotations.Entity annotation is deprecated and will be removed in a future release of Hibernate.

Hence, you should always use the @Immutabale annotation if you have entities that should never be modified by Hibernate.

The @Immutable annotation tells Hibernate to load entities in read-only mode, hence entity modifications cannot be tracked by the dirty checking mechanism.

However, the @Immutable entities can still be updated via JPQL or Criteria API bulk update queries.

To make sure @Immutabale entities are never modified for bulk update queries, from Hibernate 5.2.17 onwards, you can set the following configuration property:

<property
    name="hibernate.query.immutable_entity_update_query_handling_mode"
    value="exception"
/>

With this property in place, a bulk update query will end up throwing an exception and the entity update will be prevented.

Share:
24,652

Related videos on Youtube

non sequitor
Author by

non sequitor

Updated on July 09, 2022

Comments

  • non sequitor
    non sequitor almost 2 years

    What is the difference between the two if any?

    Should one or both be used on an entity?

  • non sequitor
    non sequitor over 14 years
    Yup I have a print out of the same doc but it does not distinguish btw the 2, just states what they are and what they can do, in this case they both do the same thing for entity(with @immutable applying to collections as well).
  • ChssPly76
    ChssPly76 over 14 years
    It's not well documented, no. EntityBinder source comments describe the above mentioned priority.
  • Michał Schielmann
    Michał Schielmann over 3 years
    hi @Vlad Mihalcea - I assume I know the answer, but is there any way to have exception thrown on regular updates to @Immutable? (instead of updates just being ignored)
  • Vlad Mihalcea
    Vlad Mihalcea over 3 years
    That's a good idea. You should open a Jira issue for it and provide a Pull Request with a fix. I'm no longer working for Red Hat, so I can't help you with this.
  • Michał Schielmann
    Michał Schielmann over 3 years
    Thank you @Vlad Mihalcea. BTW congratulations on becoming a Java Champion, well deserved.
  • Vlad Mihalcea
    Vlad Mihalcea over 3 years
    Thank you very much