Hibernate JPA @Immutable Example

@Immutable

The @Immutable annotation is used to specify that the annotated entity, attribute, or collection is immutable.

Immutable
Mark an Entity, a Collection, or an Attribute type as immutable. No annotation means the element is mutable.
An immutable entity may not be updated by the application. Updates to an immutable entity will be ignored, but no exception is thrown. @Immutable must be used on root entities only.

@Immutable placed on a collection makes the collection immutable, meaning additions and deletions to and from the collection are not allowed. A HibernateException is thrown in this case.

An immutable attribute type will not be copied in the currently running Persistence Context in order to detect if the underlying value is dirty. As a result loading the entity will require less memory and checking changes will be much faster.
Mark an Entity, a Collection, or an Attribute type as immutable. No annotation means the element is mutable.
An immutable entity may not be updated by the application. Updates to an immutable entity will be ignored, but no exception is thrown. @Immutable must be used on root entities only.

@Immutable placed on a collection makes the collection immutable, meaning additions and deletions to and from the collection are not allowed. A HibernateException is thrown in this case.

An immutable attribute type will not be copied in the currently running Persistence Context in order to detect if the underlying value is dirty. As a result loading the entity will require less memory and checking changes will be much faster.

Immutability
Immutability can be specified for both entities and collections.

Entity immutability

If a specific entity is immutable, it is good practice to mark it with the @Immutable annotation.

Immutable entity

@Entity(name = "Event")
@Immutable
public static class Event {

@Id
private Long id;

private Date createdOn;

private String message;

//Getters and setters are omitted for brevity

}
Internally, Hibernate is going to perform several optimizations, such as:

reducing memory footprint since there is no need to retain the dehydrated state for the dirty checking mechanism

speeding-up the Persistence Context flushing phase since immutable entities can skip the dirty checking process

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation