Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.persistence Annotations on field, getter or setter?

Tags:

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;
    }
}
like image 696
James McGuigan Avatar asked Jan 22 '12 22:01

James McGuigan


1 Answers

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 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?.

like image 151
JB Nizet Avatar answered Sep 28 '22 06:09

JB Nizet