Hibernate id annotation
In this section, you will learn how to do mapping of id through annotation.
Since id / primary key is the most important field in the table, it uniquely identify a row in the table. You can also auto generate this using annotation @GeneratedValue. Given below a simple class file mapped to table Worker using annotation :
package worker;
import javax.persistence.*;
@Entity
@Table(name = "Worker")
public class Worker {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public Worker() {
}
public Worker(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String first_name) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String last_name) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
Here, we are importing javax.persistence to annotate the above class. @Id annotation determines the primary key of entity.
The annotation @Id can be applied to one of the following field type :
- Java primitive type
- any primitive wrapper type
- String
- java.util.Date
- java.sql.Date
- java.math.BigDecimal
- java.math.BigInteger.