Hibernate/JPA中是否可能有不可变的字段? [英] Is it possible to have immutable fields in Hibernate/JPA?

查看:107
本文介绍了Hibernate/JPA中是否可能有不可变的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的应用程序中,我们需要具有只能分配一次的字段.

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:

  • 在没有公共设置者的情况下,Hibernate仍然能够从数据库映射字段吗?
  • 我可以剥离设置器并使字段仅在实体构造函数中可变吗?
  • 最后,有什么标准的JPA方法可以使字段不可变?

谢谢.

推荐答案

  • 广告. 1:如果将注释放在字段而非获取器上,我相信JPA会将普通私有字段用于读取和写入.最近,我发现作为基础JPA提供程序的Hibernate甚至根本不需要get*()set*()方法.因为从一开始我就认为Hibernate需要访问器,所以这确实是一个启发性的解决方案.因此答案是:就Hibernate而言,您不需要二传手.

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

      广告. 2:但是请注意,Hibernate仍然需要no-arg构造函数,否则它将无法加载具有描述性异常的实体.这也是JPA要求.

      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.

      广告. 3:不,没有.请记住,您的收藏也必须是不变的.

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

      这篇关于Hibernate/JPA中是否可能有不可变的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆