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

后端 未结 5 1627
清歌不尽
清歌不尽 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条回答
  •  Happy的楠姐
    2021-02-07 03:44

    In JPA 2.0 you have two ways to define what attributes should be persisted:

    1. Access(FIELD) - the fields name are persisted,
    2. Access(PROPERTY) - the properties name are persisted.

    If no Access(-) annotation is used, the decision what access will be used depends on where you put your @Id annotation. If you put it next to your field - Access(FIELD) will be used. If you put it next to your accessor - Access(PROPERTY) will be used.

    Therefore, if you use Access(FIELD) you don't have to have an appropriate JavaBeans-style accessor for particular field. You can have a private field named 'myField' and a public setter for it named 'public setBlahBlah(-)'. The JPA will persist just the 'myField'.

提交回复
热议问题