Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have immutable fields in Hibernate/JPA?

Tags:

In our application, we need to have fields that are assignable only once.

At first we thought of encapsulating the fields and making the setters private. However, some questions arouse:

  • Without a public setter, is Hibernate still able to map the field from the database?
  • Can I strip out the setter and make the field mutable only in the entity constructor?
  • Finally, is there any standard JPA way to make a field immutable?

Thanks in advance.

like image 668
Carlos Melo Avatar asked Oct 29 '11 19:10

Carlos Melo


People also ask

Can we create immutable class in Hibernate?

You can tell Hibernate that a specific entity is immutable by using @Entity(mutable=false) or @Immutable annotations. Note that both are Hibernate extensions to JPA standard.

What is immutable in Hibernate?

Annotation Type ImmutableMark 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.

What is @immutable in JPA?

@Immutable annotation can be used on Entity. JPA Will ignore all updates made to entity. This is a Hibernate document, not a JPA document.


2 Answers

  • Ad. 1: I believe JPA uses plain private fields for both read and write if annotations are placed on fields and not on getters. Recently I discovered that Hibernate as an underlying JPA provider does not even need get*() and set*() methods at all. This was truly enlightening solution since from the beginning I thought Hibernate needs accessors. So the answer is: you don't need setters as far as Hibernate is concerned.

  • Ad. 2: However please note that Hibernate still needs no-arg constructor, otherwise it will fail to load entities with a descriptive exception. This is also a JPA requirement.

  • Ad. 3: No, there isn't. Remember that your collections would also had to be immutable.

like image 107
Tomasz Nurkiewicz Avatar answered Sep 18 '22 17:09

Tomasz Nurkiewicz


Try

@Column(updatable = false) 

And make your setter private. (Leave your getter public if you want)

I think this is the best practice.

P.S.: JPA uses field access if you annotate your fields and uses getter/setter access if you annotate your getter method.

like image 33
KaiThomasWerther Avatar answered Sep 16 '22 17:09

KaiThomasWerther