Hibernate Annotations - Which is better, field or property access?

后端 未结 25 1557
说谎
说谎 2020-11-22 15:02

This question is somewhat related to Hibernate Annotation Placement Question.

But I want to know which is better? Access via properties or access vi

25条回答
  •  爱一瞬间的悲伤
    2020-11-22 15:28

    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";
      }
    }
    

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

提交回复
热议问题