Generator classes in Hibernate

The <generator > subelement of id used to generate the unique identifier for the objects of persistent class. There are many generator classes defined in the Hibernate Framework.

All the generator classes implements the org.hibernate.id.IdentifierGenerator interface. The application programmer may create one's own generator classes by implementing the IdentifierGenerator interface. Hibernate framework provides many implicit generator classes:


  • assigned
  • increment
  • sequence
  • hilo
  • native
  • identity
  • seqhilo
  • uuid
  • guid
  • select
  • foreign
  • sequence-identity

Assigned: It is the default generator strategy if there is no <generator > element . In this case, application assigns the id.

	
	....
 <hibernate-mapping>
  <class ...>
    <id ...>
     <generator class="assigned"></generator>
    </id>
          
    .....
          
  </class>
 </hibernate-mapping>
 

Increment: It generates the unique id just if no other process is inserting data into this table. It generates short, int or long type identifier. The first generated identifier is 1 normally and incremented as 1.

	
	....
 <hibernate-mapping>
  <class ...>
    <id ...>
     <generator class="increment"></generator>
    </id>
          
    .....
          
  </class>
 </hibernate-mapping>
 

Sequence: It uses the sequence of the database. in the event that there is no sequence defined, it creates a sequence automatically e.g. in case of Oracle database, it creates a sequence named HIBERNATE_SEQUENCE. In case of Oracle, DB2, SAP DB, Postgre SQL or McKoi, it uses sequence however it uses generator in interbase.


 .....
    <id ...>
     <generator class="sequence"></generator>
    </id>
    .....
    

Hilo: It uses high and low algorithm to generate the id of type short, int and long.

	  .....
    <id ...>
     <generator class="hilo"></generator>
    </id>
    .....
    

Native: It uses identity, sequence or hilo depending on the database vendor.

	.....
    <id ...>
     <generator class="native"></generator>
    </id>
    .....
    

Identity: It is used in Sybase, My SQL, MS SQL Server, DB2 and HypersonicSQL to support the id section. The returned id is of type short, int or long.

Seqhilo: It uses high and low algorithm on the specified sequence name. The returned id is of type short, int or long.

Uuid: It uses 128-bit UUID algorithm to generate the id. The returned id is of type String, unique inside of a network (because IP is used). The UUID is represented in hexadecimal digits, 32 long.

Guid: It uses GUID generated by database of type string. It works on MS SQL Server and MySQL.

Select: It uses the primary key returned by the database trigger.

Foreign: It uses the id of another associated object, mostly used with <one-to-one > association. </one-to-one >

Sequence-identity: It uses a special sequence generation strategy. It is supported in Oracle 10g drivers just.


Next Concept Architecture