Primary key generation in JPA

How to generate a primary key in JPA (Hibernate, Eclipselink, Toplink). IDENTITY, SEQUENCE and other strategies (AUTO, TABLE) explained.

@Id annotation marks your primary key. It is usually Integer or int, but it can be anything else. It's type must correspond to the type of the column in your table. If you want to persist some data to database, you must somehow generate this primary key. If you don't specify anything, you must do it on your own.

Or you can use annotation @GeneratedValue and let something else for you to generate your primary key. You can set it's atribute strategy to these values:

  • AUTO: Using this value it's up to your JPA implementation to generate this primary key. I seldom use this, I'd like to have primary key generation fully under my control.
  • IDENTITY: Some databases like MySQL are able to autoincrement a value of a primary key upon SQL INSERT. For MySQL use this strategy.
  • SEQUENCE: Most databases have sequences, so you can use them. If you want to use sequences, you must name a generator. This generator is defined using annotation @SequenceGenerator.
  • TABLE: If you cannot use sequences, you can use a table to be something like a sequence. Again you must define a generator, this time table generator using annotation @TableGenerator. I don't use this strategy, because nowadays every popular database has sequences.