Difference between sequence and identity in Hibernate



Hibernate or JPA support 4 different types of  primary key generator. These generators are used to generate primary key while inserting rows in the database. Below are the primary key generator  

  • GenerationType.AUTO
  • GenerationType. IDENTITY
  • GenerationType.SEQUENCE 
  • GenerationType.TABLE

GenerationType. IDENTITY − In identity , database is responsible to auto generate the primary key. Insert a row without specifying a value for the ID and after inserting the row, ask the database for the last generated ID.  Oracle 11g does not support identity key generator. This feature is supported in Oracle 12c. 

GenerationType. SEQUENCE − In sequence, we first ask database for the next set of the sequence then we insert row with return sequence id. 

Sr. No.
Key
GenerationType. IDENTITY
GenerationType.SEQUENCE

1

Basic 

 Database is responsible to auto generate the primary key

we first ask database for the next set of the sequence then we insert row with return sequence id.

2

Performance 

It is faster than sequence key generator 

It is bit slower than identity key generator

3

Database Support 

Oracle 11g does not support identity key generator

Oracle 11g does support SEQUENCE key generator

Example of GenerationType.IDENTITY

@Entity
public class User {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   Integer id;
   String name;
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

Example of GenerationType.SEQUENCE

@Entity
public class User {
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE)
   Integer id;
   String name;  
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

Advertisements