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

后端 未结 5 1551
清歌不尽
清歌不尽 2021-02-07 03:00

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 q

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 03:29

    • 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.

提交回复
热议问题