Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the difference between the two if any?

Should one or both be used on an entity?

like image 627
non sequitor Avatar asked Oct 19 '09 18:10

non sequitor


People also ask

What is mutable false in hibernate?

In hibernate, 'mutable' is default to 'true' in class and its related collection, it mean the class or collection are allow to add, update and delete. On the other hand, if the mutable is changed to false, it has different meaning in class and its related collection.

Is @entity annotation mandatory in hibernate?

The entity class must be annotated with the Entity annotation or denoted in the XML descriptor as an entity. So, if you use annotations for mappings, @Entity is mandated by the specification and Hibernate has to adhere to it.

What is the use of immutable class in hibernate?

Immutable classes are classes which state remains unchanged throughout the application lifetime. The set of class instance properties is assigned at creation and property values are never allowed to change. In other words, immutable class instances, once created, can never be modified.

What is the use of @entity in hibernate?

@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default.


2 Answers

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

like image 61
ChssPly76 Avatar answered Sep 20 '22 07:09

ChssPly76


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.

like image 35
Vlad Mihalcea Avatar answered Sep 20 '22 07:09

Vlad Mihalcea