Thursday, February 18, 2010

Hibernate Sequence Generator

Hibernate generator element generates the primary key for new record. This is used in conjunction with the Id element. Hibernate provides about 11 types of generator .Among these the Sequence generator uses the Sequence from the Database and returns identifier value of type long,short or int.

To use the Sequence from the database,need to map the field for Id, and specify the Generation Type as Sequence. By default the sequence generator provides values that are incremented in counts of 50,this can be overridden by specifying the allocationSize

@Entity( name = "EmployeeEntity" )
@SequenceGenerator( name = "id_sequence", allocationSize = 1, sequenceName = "SEQ_EMP_ID" )
@Table( name = "T_EMP_MASTER" )
public class EmployeeEntity implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "id_sequence" )
@Column( name = "emp_id" )
private Long empId;
@Column(name="firstName")
private String firstName;
@Column(name="lastName")
private String lastName;
//Getters and Setters
}