Skip to content

Hibernate/JPA Annotations

July 29, 2010

Today I’m going to talk about how to use Hibernate/JPA annotations. We will have different articles on these annotations starting with basics to more advanced use of annotations. Most of the Hibernate annotations are similar to the ones found in the JPA specification and i will specifically mention whenever i will use the one doesn’t exist in both.

Let’s start with the simple annotations you will need to map your objects. Following is a comprehensive list of basic entities you will need to persist your POJOs.

  1. Entity
  2. Table
  3. Id and GeneratedValue
  4. Column
  5. Transient
  6. Enumerated
  7. Temporal
  8. Type
  9. Basic

Entity, Table and Id Annotations

Every POJO that you want to persist in the database should have been marked with @Entity annotation. This annotation mark your POJO ready for the persistence.

The POJO to which you will apply @Entity annotation should also have @Table annotation which is used to specify in which table your POJO data will be saved in. @Table annotation has the following attributes:

  • name: This attribute is used to specify the name of the target table.
  • uniqueConstraints: This attribute is used to specify the unique constraints you have on your table.

You could have many objects of same entity each with his own unique id, so you will also use @Id and @GeneratedValue annotations to set the unique identification and type that will be used for its generation as shown in the following example:

package org.learn.java.jpa.annotations.basics;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name="user")
public class User {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
       @Column(name = "id")
	private int id;

}

@GeneratedValue annotation is used to specify how the unique identification of each record inserted by your POJO will be created? As you can see from above example it has an attribute named strategy which could have following possible values:

  • AUTO: This strategy is used to utilize the database underlying properties to create unique keys. It could be auto increment columns, sequence, and other possible features of the database to create unique identification for each rows. AUTO strategy is the easiest way of generating object keys and is also the most portable way of creating these keys. However, the problem with using AUTO is, your objects will not get the id until you have executed them using EntityManager. This is because databases create the ids for identity columns when they get the insert statement.
  • IDENTITY: This strategy is used to specify an identity column that will be used to get the unique identification of each row. Different databases support identity columns such as MySQL, Postgres, SQL Server, and DB2. However, Oracle doesn’t support IDENTITY column, it support sequence instead. This is not the portable way across all database so if you are planning to use Oracle be careful of using IDENTITY.
  • SEQUENCE: If you want to use SEQUENCE strategy than you will need to specify the generator name and another annotation @SequenceGenerator will be used to specify further information of your sequence. @SequenceGenerator has three attributes a) name, this will be the same as you would have mentioned in the name attribute of your SEQUENCE strategy. b) sequence_name, this is the name of the sequence and c) allocation_size, this will be the starting point of your sequence.
  • TABLE: This is like the sequence generator in a way that you will need to specify a new annotation @TableGenerator if your strategy is TABLE. @TableGenerator has five attributes a) name b) table, this is the name of the table which will be used to create keys c) pkColumnName, is used to specify the name of primary key column d) valueColumnName, is used to specify the sequence value column name e) pkColumnValue, is used to specify the row value which will contain the value of the sequence.

Following is a sample code with the table which can be used if your identification strategy is TABLE:

package org.learn.java.jpa.annotations.basics;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

@Entity
@Table(name = "user")
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.TABLE, generator = "usr_tab_seq")
	@TableGenerator(name = "usr_tab_seq", table = "seq_tab", pkColumnName = "seq_name", valueColumnName = "seq_val", pkColumnValue = "usr_seq")
	private int id;

}

Sequence Table

Column, Basic, and Transient Annotations

@Column annotation is used to map the property of your POJO with the table columns. You don’t need to use @Column annotation if the name of your POJO property is same as the name of the column in the table. If this is not the case than you will need to explicitly map properties of POJO with table columns using the @Column annotation. @Column annotation has the following generally used attributes:

  • name: is used to specify the name of the column in the table in which current property data will be saved.
  • unique: is used to specify if the current column is unique
  • nullable: is used to specify if the current column can contain null values
  • updatable: is used to specify if the current column value can be updated

@Basic is used to specify the fetching strategy of your POJO properties. You can specify either LAZY or EAGER fetching strategy. I will discuss the fetching strategies in detail in next part of this series. By default every non-static property of your POJO will be persisted unless you marked it with @Transient annotations.

Enumerated, Temporal, and Type Annotations

@Enumerated annotation is used for the Enum type properties of your POJO. You can save the enum ordinal position in your table or the value of the enum. @Temporal is used for DATE, TIME or TIMESTAMP, you can specify the type using its TemporalType property.

@Type annotation is used to specify the data type class that will be used to persist current property. This is not JPA annotation rather then it is hibernate annotation. An example of you using this could be, you want to use JODA DateTime class to represent user creation and modification dates which you later on uses for different operations supported by JODA library.

Following example shows all the annotations we have discussed so far:

package org.learn.java.jpa.annotations.basics;

import java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Type;
import org.joda.time.DateTime;

@Entity
@Table (name="user")
public class User {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
	private int id;

    private String username;

    private String password;

    @Column(name = "first_name", unique = false, nullable = false, updatable = true)
    @Basic (fetch = FetchType.EAGER)
    private String firstName;

    @Column(name = "last_name", unique = false, nullable = false, updatable = true)
    @Basic (fetch = FetchType.LAZY)
    private String lastName;

    @Enumerated (EnumType.ORDINAL)
    private UserType userType;
    
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "last_logon", nullable = false)
    private Date lastLogon;
    
    @Column(name = "creation_date", nullable = false, updatable = false)
    @Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
    private DateTime creationDate;

    @Column(name = "modification_date", nullable = false)
    @Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
    private DateTime modificationDate;

}

To compile above code make sure you have following jar files in your classpath:

  • ejb3-persistence.jar
  • hibernate-annotations.jar
  • joda-time-version.jar
  • joda-time-hibernate-version.jar

Take care until the next part of this article in which we will discuss Collections and other JPA annotations.

Advertisements

From → Java, Programming

3 Comments
  1. Imran Mirza permalink

    Good one. One can easily understand Annotation specifically Hibernate Annotation….

  2. Bharatkumar Patel permalink

    Good One !!! Nice Explanation. Where can I find Collections and other JPA annotations.

    • skhanzada permalink

      I will post next part of this series in couple of weeks, so keep visiting or subscribe!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: