問題描述
這個問題與Hibernate Annotation Placement Question有些相關.
但我想知道哪個更好?通過屬性訪問還是通過字段訪問?各有什么優缺點?
But I want to know which is better? Access via properties or access via fields? What are the advantages and disadvantages of each?
推薦答案
我更喜歡訪問器,因為我可以在需要時向訪問器添加一些業務邏輯.這是一個例子:
I prefer accessors, since I can add some business logic to my accessors whenever I need. Here's an example:
@Entity
public class Person {
@Column("nickName")
public String getNickName(){
if(this.name != null) return generateFunnyNick(this.name);
else return "John Doe";
}
}
此外,如果您將其他庫放入混合中(例如一些 JSON 轉換庫或 BeanMapper 或 Dozer 或其他基于 getter/setter 屬性的 bean 映射/克隆庫),您將保證該庫是同步的使用持久性管理器(都使用 getter/setter).
Besides, if you throw another libs into the mix (like some JSON-converting lib or BeanMapper or Dozer or other bean mapping/cloning lib based on getter/setter properties) you'll have the guarantee that the lib is in sync with the persistence manager (both use the getter/setter).
這篇關于Hibernate Annotations - 哪個更好,字段訪問還是屬性訪問?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!