Search code examples
javahibernate-mapping

javax.persistence Annotations on field, getter or setter?


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;
    }
}

Solution

  • 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 preferable, 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?.