JPA Hibernate Mapping Annotations

By | | Updated : 2020-01-05 | Viewed : 401 times

JPA Hibernate Mapping Annotations

We need to understand all the important annotations when we are writing an application using an ORM tool such as Hibernate application. JPA-HIbernate Mapping Annotations are very important nowadays as XML configurations are separated from the Java code files. You might aware that Annotations are neat and readable. In this post, We will discuss all the important JPA-Hibernate Mapping Annotations with examples.

JPA Annotations

@Entity

This annotation is used to represent the Class as an entity. The name attribute is optional here.

Example annotation for Entity
import javax.persistence.Entity;

@Entity(name="author")
public class Author implements Serializable {
}

@Table

This annotation represents the database table of the entity class. Here name attribute should be the name of the database table.

Example for @Table Annotation
import javax.persistence.Entity;
 import javax.persistence.Table;

@Entity
@Table(name = "author")
public class Author implements Serializable {
}

@Column

This annotation defines the Database column. The name attribute is used for specifying the table’s column name.

Example code for @Column
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
 
	@Column(name = "employee_name")
	private String employeeName;
}

@Id

This annotation represents the primary key of the table.

@GeneratedValue

This annotation will specify the type/strategy of the primary key generation.

Example for Primary Key Generation
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;

@Entity
@Table(name = "author")
public class Author implements Serializable { 
  	@Id
  	@GeneratedValue(strategy=SEQUENCE,   generator="AUTHOR_ID_SEQ")
  	@Column(name = "author_id")
  	private int authorId;
}

Annotations for Identifier

JPA provides four types of identifier generation strategies. These strategies describe how the Primary key value should be generated. Some of them are

  1. Auto

  2. Identity

  3. Sequence

  4. Table

Auto

Example code for Auto Generation Strategy
	@Id	
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "author_id", updatable = false, nullable = false)
	private Long authorId;

This is the default type of Generation strategy. Based on the type of Database Dialect the Generation Strategy i.e., Primary key generation strategy will be chosen.

Identity

Example code for Identity Generation Strategy
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "author_id", updatable = false, nullable = false)
    	private Long authorId;

The Primary Key of Entity will be database column identity which means Primary Key value should be the auto Incremented value of the column in Database.

Sequence

Example code for Sequence Generation Strategy
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "author_id", updatable = false, nullable = false)
	private Long authorId;

The Primary key value of Entity is assigned from the Database Sequence. The sequence in the database handles the generation of the primary key value.

Table

Example code for Table Generation Strategy
	@Id
	@GeneratedValue(strategy = GenerationType.TABLE, generator = "author_generator")
	@TableGenerator(name="author_generator", table="author_id_generator", schema="hibernate_tutorials")
	@Column(name = "id", updatable = false, nullable = false)
	private Long authorId;

This strategy will generate the primary key value by using another table. @TableGenerator is used for configuration of the Generator Table.

To know more about the Generation Strategies please see details here Identifier Generation Strategies

@OrderBy

To Sort the data this annotation will be used for. Here we need to pass the column. So the select query will be fired by adding order by the condition.

Example code for @OrderBy
	@OrderBy("bookId")
	private List<Book> bookList= new ArrayList<>();

@Version

This annotation will be used for versioning of a field. So we can avoid inconsistent data where merge operation placed. It will be served as an Optimistic lock.

Example code for @Version
@Entity
@Table(name = "book")
public class Book implements Serializable {
 	 @Version
 	 @Column(name = "published_date ")
 	 private publishedDate version;
}

@Transient

To make a field a non-persistent then we can annotate the field with @Transient

Example code for @Transient
@Transient
Private String passWord;

Annotations for Associations

In Hibernate, three types of annotations are provided for making association one entity with another.

  1. @OneToOne

  2. @ManyToOne

  3. @OneToMany

  4. @ManyToMany

@OneToOne

We will take an example of considering the below-given relationship.Book has one BookDetails i.e., Book has OneToOne association with BookDetails. In this case, both entities are sharing the same primary keys. So here we can use @OneToOne and @PrimaryKeyJoinColumn

Example code for @OneToOne
@Entity
@Table(name = "book")
public class Book implements Serializable {
   
  	@Id
  	@Column(name = "book_id")
	@GeneratedValue
  	private int bookId;
   
  	@OneToOne(cascade = CascadeType.MERGE)
  	@PrimaryKeyJoinColumn
  	private BookDetail bookDetail ;
	}

We understood the above situation where two associated entities have the same primary key then we can use @PrimaryKeyJoinColumn. If one of the entities is holding the foreign key then we can use @JoinColumn and @OneToOne with mappedBy attribute. Please examine the below-given example.

Example code for @OneToOne
@Entity
@Table(name = "book_detail")
public class BookDetail implements Serializable {
 
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int bookDetailId;
   
  @OneToOne
  @MapsId
  @JoinColumn(name = "book_id")
  private Book book;
}
 

In the below-given example, we have created a two-way relationship.

Example code for @OneToOne Bi-directional
@Entity
@Table(name = "book")
public class Book implements Serializable {
 
 @Id
 @Column(name = "ID")
 @GeneratedValue
  private Integer bookId;
 
  @OneToOne(mappedBy = "book", cascade = CascadeType.ALL)
  private BookDetail  bookDetail;
 }

@ManyToOne

One author can write so many books. So we can describe the ManyToOne relationships like Many books can be written by one Author

Example code for @ManyToOne
@Entity
@Table(name = "employee")
public class Book implements Serializable {
 
  @ManyToOne
  @JoinColumn(name = "author_Id")
  private Author author;
}

@OneToMany

Author to Book can be defined by the relationship called one-to-many. As the owner of the relationship is a book so, we can use mappedBy in Author to make a two-way relationship

Example code for @OneToMany
@Entity
@Table(name = "auhor")
public class Author implements Serializable {
 
  @OneToMany(mappedBy = "book", fetch = FetchType.EAGER)
  @OrderBy("firstName asc")
  private Set books;
}

@MapsId:Two entities with a shared key can be persisted using @MapsId annotation.

@ManyToMany

Author and Book entities can be defined with ManyToMany relationship by using Third table called Auth-Book table.

We can make association bidirectional as well as unidirectional. Please see the below given example for unidirectional.

Example code for @ManyToMany
@ManyToMany 
@JoinTable( 
name=" AUTHOR_BOOK", 
joinColumns= @JoinColumn(name=" AUTHOR_ID", referencedColumnName="ID"), 
inverseJoinColumns= @JoinColumn(name=" BOOK_ID", referencedColumnName="ID") ) 
private List books = new ArrayList();

Inheritance Mapping

Single table

In this inheritance Mapping, all the Base and Sub Classes map to the only one Database table. Hibernate uses the discriminator column to differentiate the super and Sub class entities.

Example code for Single table
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="bookType", discriminatorType=DiscriminatorType.STRING )
 
@DiscriminatorValue("bookType")
public class Book{ }

So in the Sub Class, we should define the value for the discriminator column.

Example code for Single table
@Entity
@DiscriminatorValue("FictionBook")
public class FictionBook extends Book{ }

@Entity
@DiscriminatorValue("NonFictionBook ")
public class NonFictionBook extends Book{ }

Joined table / Table Per Subclass

In this Inheritance Mapping, every Base and Sub Class have their database table. Sub Classes have one common primary key which is a foreign key to the BaseClass. When querying for Sub Class then this common column will be used.

Example code for Joined table / Table Per Subclass
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Book{
    @Id
    private long bookId;   
    
}

and subclass should be as given below.

Example code for Joined table / Table Per Subclass
@Entity
public class FictionBook extends Book {
    private String name;
   
}

Table per class / Table per concrete class

In this Inheritance Mapping, each class represents one table. Each subclass has the property of the Base class.

Example code for Table per class / Table per concrete class
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Aeroplane implements Serializable {}
Leave A Reply