javax.persistence对field,getter或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的所有注释