JPA需要实体类的getter和setter方法。

huangapple go评论75阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年2月19日 18:07:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定