javax.persistence Annotations on field, getter or setter?

后端 未结 2 1238
遇见更好的自我
遇见更好的自我 2021-02-07 05:14

I am currently learning Hibernate and the Java Persistence API.

I have an @Entity class, and need to apply annotations to the various fields. I have included in the code

相关标签:
2条回答
  • 2021-02-07 05:44

    You have to put annotations only for field or only for getter

    @Id 
    @Column(name="id", unique=true, nullable=false)
    private int    id;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    

    or

    private int    id;
    
    @Id 
    @Column(name="id", unique=true, nullable=false)
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    

    And for all fields/properties in same way. All annotations for fields or all annotations for getter

    0 讨论(0)
  • 2021-02-07 05:51

    You have to choose between field and getter. Annotations on setters are not supported. And all the annotations should be on fields, or they should all be on getters: you can't mix both approaches (except if you use the @AccessType annotation).

    Regarding which one is preferrale, the answer is: it depends. I prefer field access, but YMMV, and there are situations where property access is preferrable. See Hibernate Annotations - Which is better, field or property access?.

    0 讨论(0)
提交回复
热议问题