JPA annotations are used in mapping java objects to the database tables, columns etc. Hibernate is the most popular implement of JPA specification and provides some additional annotations. Today we will look into JPA annotations as well as Hibernate annotations with brief code snippets.
Java annotation is a form of metadata that can be added to Java source code. Java annotations can be read from source files. It can also be embedded in and read from class files generated by the compiler. This allows annotations to be retained by JVM at run-time. JPA annotations are not part of standard JDK, so you will get it when you add any implementation framework. For example, below hibernate maven dependency will get you JPA annotations too.
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
Let us look at some of the important JPA annotations. Note that these annotations are present in javax.persistence
package.
javax.persistence.Entity
: Specifies that the class is an entity. This annotation can be applied on Class, Interface of Enums.
import javax.persistence.Entity;
@Entity
public class Employee implements Serializable {
}
@Table
: It specifies the table in the database with which this entity is mapped. In the example below the data will be stores in the “employee” table. Name attribute of @Table annotation is used to specify the table name.
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
}
@Column
: Specify the column mapping using @Column annotation. Name attribute of this annotation is used for specifying the table’s column name.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Column(name = "employee_name")
private String employeeName;
}
@Id
: This annotation specifies the primary key of the entity.
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id")
private int id;
}
@GeneratedValue
: This annotation specifies the generation strategies for the values of primary keys.
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy=SEQUENCE, generator="ID_SEQ")
private int id;
}
@Version
: We can control versioning or concurrency using this annotation.
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Version
@Column(name = "version")
private Date version;
}
@OrderBy
: Sort your data using @OrderBy annotation. In example below, it will sort all employees_address by their id in ascending order.
@OrderBy("id asc")
private Set employee_address;
@Transient
: Every non static and non-transient property of an entity is considered persistent, unless you annotate it as @Transient.
@Transient
Private int employeePhone;
@Lob
: Large objects are declared with @Lob.
@Lob
public String getEmployeeAddress() {
return employeeAddress;
}
The above set of annotation are most commonly used JPA annotations to define an entity.
We have another set of annotations that are used to specify the association mapping between different tables and entities. We will take an example considering the below mentioned scenario.
@OneToOne
Employee and EmployeeDetail entities share the same primary key and we can associate them using @OneToOne and @PrimaryKeyJoinColumn. In this case the id property of EmployeeDetail is not annotated with @GeneratedValue. The id value of Employee will be used for used for id of EmployeeDetail.
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@OneToOne(cascade = CascadeType.MERGE)
@PrimaryKeyJoinColumn
private EmployeeDetail employeeDetail;
}
@Entity
@Table(name = "employeeDetail")
public class EmployeeDetail implements Serializable {
@Id
@Column(name = "id")
private int id;
}
Points to note:
Communication and CommunicationDetail are linked through a foreign key, so @OneToOne and @JoinColumn annotations can be used. In snippet mentioned below, the id genereated for Communication will be mapped to ‘communication_id’ column of CommunicationDetail table. @MapsId is used for the same.
@Entity
@Table(name = "communicationDetail")
public class CommunicationDetail implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@OneToOne
@MapsId
@JoinColumn(name = "communicationId")
private Communication communication;
}
@Entity
@Table(name = "communication")
public class Communication implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue
private Integer id;
@OneToOne(mappedBy = "communication", cascade = CascadeType.ALL)
private CommunicationDetail communicationDetail;
}
@ManyToOne
Many employees can share the same status. So, employee to employeeStatus is a many to one relation. @ManyToOne annotation can be used for the same.
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@ManyToOne
@JoinColumn(name = "statusId")
private EmployeeStatus status;
}
@OneToMany
Employee to Communication will be a one-to-many relationship. The owner of this relationship is Communication so, we will use ‘mappedBy’ attribute in Employee to make it bi-directional relationship.
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
@OrderBy("firstName asc")
private Set communications;
}
@PrimaryKeyJoinColumn
This annotation is used to associate entities sharing the same primary key.
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@OneToOne(cascade = CascadeType.MERGE)
@PrimaryKeyJoinColumn
private EmployeeDetail employeeDetail;
}
@JoinColumn
@JoinColumn annotation is used for one-to-one or many-to-one associations when foreign key is held by one of the entities.
@ManyToOne
@JoinColumn(name = "statusId")
private EmployeeStatus status;
@JoinTable
: @JoinTable and mappedBy should be used for entities linked through an association table. @MapsId
: Two entities with shared key can be persisted using @MapsId annotation.
@OneToOne
@MapsId
@JoinColumn(name = "communicationId")
private Communication communication;
Now let us try to understand the inheritance mapping annotation in Hibernate. Hibernate supports the three basic inheritance mapping strategies:
we will consider example for each type.
Table per class hierarchy - single table per Class Hierarchy Strategy.
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING )
@DiscriminatorValue("Car")
public class Car { }
@Entity
@DiscriminatorValue("BMW")
public class BMW extends Car { }
Table per class/subclass - joined subclass Strategy.
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Ship implements Serializable {}
@Entity
@PrimaryKeyJoinColumn
public class Titanic extends Ship {}
Table per concrete class.
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Aeroplane implements Serializable {}
@DiscriminatorColumn: As the name suggests this column is the descriminator and this annotation specifies the discriminator column for the SINGLE_TABLE and JOINED Inheritance mapping strategies.
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING )
That’s all for JPA and Hibernate annotations. Reference: JSR 338, Hibernate API Docs
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Hi Pankaj, I am going through your website for Hibernate , Spring and other technologies as well. Your explanation is very nice and understandable. Can you please add your detailed knowledge on Inheritence mapping of Hibernate. It is missing actually frim hibernate section. Thanks in Advance Md Manzer Imam
- Md Manzer Imam
It should be noted that we should always strive to use JPA annotations instead of the Hibernate ones, unless there is something very specific about the Hiberanate function that is not provided through JPA. And having said that, as soon as JPA does include that functionality, the Hibernate annotations should be changed. For a bit of an overview of some of the differences between JPA and Hibernate, please take a gander at an article I wrote about the subject: https://www.theserverside.com/video/JDBC-vs-ODBC-Whats-the-difference-between-these-APIs
- Cameron McKenzie
yes,its ultimate sir…thank you
- shivasharan
very good explanation
- Nissi
This tutorial is really helpful sir Thank you sir
- Haris faiz