[英]javax.persistence Annotations on field, getter or setter?
我目前正在學習Hibernate和Java Persistence API。
我有一個@Entity類,需要將注釋應用於各個字段。 我已經在下面的代碼中包含了他們可以去的所有三個地方。
我應該將它們應用於場地本身,吸氣劑還是定位器? 這三個選項之間的語義差異(如果有的話)是什么。
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;
}
}
你必須在場和吸氣器之間做出選擇。 不支持setter上的注釋。 並且所有注釋都應該在字段上,或者它們都應該在getter上:您不能混合使用兩種方法(除非您使用@AccessType
注釋)。
關於哪一個更喜歡,答案是:它取決於。 我更喜歡現場訪問,但YMMV,並且有些情況下屬性訪問是可取的。 請參閱Hibernate Annotations - 哪個更好,字段或屬性訪問? 。
您必須僅為字段或僅為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;
}
要么
private int id;
@Id
@Column(name="id", unique=true, nullable=false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
並以相同的方式為所有領域/屬性。 字段的所有注釋或getter的所有注釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.