javax.persistence Annotations on field, getter or setter?

≯℡__Kan透↙ 提交于 2019-12-09 05:10:38

问题


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 below all three places where they could go.

Should I apply them to the field itself, the getter or the setter? And what is the semantic difference, if any, between these three options.

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;

@Entity
@Table(name = "song")
public class Song { 
    // Annotations should only be applied to one of the below

    @Id 
    @Column(name="id", unique=true, nullable=false)
    private int    id;

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

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

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/8965116/javax-persistence-annotations-on-field-getter-or-setter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!