JPA/HB – annotations
In this tutorial, we will learn about JPA as well as Hibernate annotations. We use these annotations to map classes to tables, data members to columns, primary key etc. Let’s have a look at some of the most commonly used annotations.
Below annotations belong to javax.jpa pacakage.
1. @Entity – This can be applied on a class, interface or enum. This specifies that the class is an Entity. Entity is a business object and it has a related table in the database.
import javax.persistence.Entity;
@Entity
public class Teacher implements Serializable {
}
2. @Table – This implies that the entity class is mapped to a table in the database. ‘Name’ attribute of this annotation is used to tell the name of the table.
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "teacher")
public class Teacher implements Serializable {
}
3. @Column – This maps a data member of entity class to a database column. The ‘Name’ attribute of this annotation is used to specify the name of the related column.
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
@Entity
@Table(name = "teacher")
public class Teacher implements Serializable {
@Column(name = "teacher_name")
private String name;
}
4. @Id – This specifies the primary key in the table. It maps the data member of entity class to primary key in the table.
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Id;
@Entity
@Table(name = "teacher")
public class Teacher implements Serializable {
@Id
@Column(name = "teacher_id")
private int id;
}
5. @GeneratedValue – This specifies the strategy in which the primary key should be generated. This annotation has two optional attributes ‘strategy‘ and ‘generator‘.
Strategy – Primary key generation strategy
generator – Name of the primary key generator. To learn more about Generation strategy of primary keys, please click here.
import javax.persistence.*;
@Entity
@Table(name = "teacher")
public class Teacher implements Serializable {
@Id
@Column(name = "teacher_id")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "custom-seq")
private int id;
}
import javax.persistence.*;
@Entity
@Table(name = "teacher")
public class Teacher implements Serializable {
@Id
@Column(name = "teacher_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
}
6. @OrderBy – used to order the elements in ascending as well as descending order. To learn in detail click here.
@OrderBy("subjectId desc")
private List<Subject> subjects;
@OrderBy("subjectId asc")
private List<Subject> subjects;
7. @Lob – used to decalre the large objects
@Lob
public String getTeacherAddress() {
return teacherAddress;
}
8. @Transient – If we do not want to persist a particular property of an entity class, then we have to declare it as transient.
@Transient
private String surName;