英文:
JPA required getters and setters for the entity class
问题
@Entity类是否必须始终具有getter和setter,并且所有属性都应该是私有的?JPA(或Hibernate)是否要求这些方法(getter/setter)来获取值或将其设置到数据库中?
英文:
I am new to the Spring ecosystem and I wonder if the @Entity class should always have getters and setters and that all the properties should be private? Is it correct that the JPA(or Hibernate) will require those methods (getters/setters) to fetch the values or set them in the database ?
答案1
得分: 2
来自JakartaEE JPA 3.0规范,第2.2节:持久字段和属性:
2.2. 持久字段和属性
实体的持久状态由持久性提供程序运行时访问,可以通过JavaBeans风格的属性访问器("属性访问")或通过实例变量("字段访问")来访问。...
...
一个类的实例变量必须具有私有、受保护或包可见性,无论是使用字段访问还是属性访问。当使用属性访问时,属性访问器方法必须是公共的或受保护的。
这意味着访问器不是严格要求的,但强烈建议使用。另一种方法(字段访问)被视为代码异味。
英文:
From the JakartaEE JPA 3.0 specification, §2.2.: Persistent Fields and Properties:
> ### 2.2. Persistent Fields and Properties
>
> The persistent state of an entity is accessed by the persistence provider runtime<sup>[1]</sup> either via JavaBeans style property accessors (“property access”) or via instance variables (“field access”). ...
>
> ...
>
> The instance variables of a class must be private, protected, or package visibility independent of whether field access or property access is used. When property access is used, the property accessor methods must be public or protected.
>
> ....
This means that accessors are not strictly required, but highly recommended. The alternative (field access) is regarded as a code smell.
答案2
得分: -1
是的,你应该使用 @entity,它还有助于其他人阅读你的代码,它对其进行了文档化,你还可以使用 Lombok 中的 private 和 @Data 注解(用于自动生成 Getter/Setter)。
英文:
Yes you should use @entity, it also helps for others when they read your code, it documents it, you use private and @Data annotation from Lombok (to auto generate Getter/setter)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论