Hibernate @Immutable Entities

Learn to use the Hibernate @Immutable annotation to create immutable entities, similar to immutable classes in Java, a rather well-known concept.

Note that immutability can be specified for both entities and collections.

1. Immutable Entities

1.1. When to Use Immutable Entities

The @Immutable annotation marks an entity as being, well, immutable. This is useful for situations where an entity represents reference data–things like lists of states, genders, or other rarely mutated data.

Since things like states tend to be rarely changed, someone usually updates the data manually, via SQL or an administration application. Hibernate can cache this data aggressively, which needs to be taken into consideration; if the reference data changes, we would want to make sure that the applications using it are notified (may use refresh() method) or restarted somehow.

Hibernate ensures that any updates to an immutable entity should not be passed on to the database without giving any error. Generally, no SQL UPDATE statement is executed in case an immutable entity is updated.

@Immutable can be placed on a collection too; in this case, changes to the collection (additions, or removals) will cause a HibernateException to be thrown.

1.2. Performance Gains

Hibernate performs several optimizations for immutable entities such as:

  • reducing memory footprint since there is no need to retain the dehydrated state for the dirty checking mechanism
  • speeding-up the flushing phase since immutable entities can skip the dirty checking process

2. Using @Immutable

We can apply the @Immutable annotation in two places:

  • On Entity class declaration
  • On Collection type fields

Let’s check out the example of both placements.

@Entity
@Immutable
public class Notification {

   @Id
   private Long id;

   private Date createdOn;

   private String message;

   //Getters and setters are omitted for brevity
}

Once the immutable collection is created, it can never be modified. Note that in this example, the Transaction entity is mutable, only notifications collection is immutable.

@Entity
public static class Transaction {

   @Id
   private Long id;

   @OneToMany(cascade = CascadeType.ALL)
   @Immutable
   private List<Notification> notifications = new ArrayList<>();

   //Getters and setters are omitted for brevity
}

It is worth remembering that while immutable entity changes are simply discarded, modifying an immutable collection will end up in a HibernateException being thrown.

Happy Learning !!

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

Leave a Comment

About HowToDoInJava

This blog provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.