问题描述
我目前正在学习Hibernate和Java Persistence API。
I am currently learning Hibernate and the Java Persistence API.
我有一个@Entity类,需要对各个字段应用注释。我已经在下面的代码中包含了他们可以去的所有三个地方。
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.
我应该将它们应用到字段本身,getter还是setter?这三个选项之间的语义差异是什么(如果有的话)。
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;
}
}
推荐答案
你必须在场和吸气之间做出选择。不支持在setter上添加注释。并且所有注释都应该在字段上,或者它们都应该在getter上:你不能混合两种方法(除非你使用注释)。
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).
关于哪一个更喜欢,答案是:它取决于。我更喜欢现场访问,但YMMV,并且有些情况下属性访问是可取的。请参阅。
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?.
这篇关于javax.persistence对field,getter或setter的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!