简体   繁体   English

javax.persistence对field,getter或setter的注释?

[英]javax.persistence Annotations on field, getter or setter?

I am currently learning Hibernate and the Java Persistence API. 我目前正在学习Hibernate和Java Persistence API。

I have an @Entity class, and need to apply annotations to the various fields. 我有一个@Entity类,需要将注释应用于各个字段。 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;
    }
}

You have to choose between field and getter. 你必须在场和吸气器之间做出选择。 Annotations on setters are not supported. 不支持setter上的注释。 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). 并且所有注释都应该在字段上,或者它们都应该在getter上:您不能混合使用两种方法(除非您使用@AccessType注释)。

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. 我更喜欢现场访问,但YMMV,并且有些情况下属性访问是可取的。 See Hibernate Annotations - Which is better, field or property access? 请参阅Hibernate Annotations - 哪个更好,字段或属性访问? .

You have to put annotations only for field or only for getter 您必须仅为字段或仅为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 字段的所有注释或getter的所有注释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM