Menu

Primary Keys and Generation Strategies

Primary Keys and Generation Strategies

Generated Keys

Most entities let the database or Hibernate produce the key. This is done with @GeneratedValue, and the strategy decides how the value is created.

Strategy

How the key is produced

AUTOHibernate chooses based on the key type and database
IDENTITYAuto-increment column in the database
SEQUENCEDatabase sequence
TABLEA separate table that holds key values
UUIDA generated UUID

Choosing a Strategy

SEQUENCE is usually the best choice where the database supports it. Hibernate can reserve a block of values at once, so it does not need a database call for every insert.

IDENTITY is simple, but the insert must run immediately to obtain the key.

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "student_seq")
@SequenceGenerator(name = "student_seq", sequenceName = "student_seq", allocationSize = 50)
private Long id;

@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID uuid;

Code Explanation:

  • The first key uses a sequence named student_seq.
  • allocationSize = 50 means Hibernate takes 50 values per database call. The sequence must use the same increment.
  • The second key shows the UUID strategy, which needs no sequence or auto-increment column.
  • With AUTO on a Long key, Hibernate 6 and later use a sequence named after the entity, such as Student_SEQ.

For keys made of several columns, use @EmbeddedId with an embeddable class, or @IdClass.


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details