Why we use @GeneratedValue ?

Hibernate supports different type of generation strategies to generate a primary key in the database table (MySQL / Oracle / PostgreSQL…).

Using the annotation @GeneratedValue we can specifies how to generate values for the given column

//Syntaxe 
 @Id 
 @GeneratedValue  
 @Column(name="id")   
 private int id;  

With @GeneratedValue annotation we have to set two parameters, strategy, and GenerationType. The GenerationType is an enum which defines the types of strategies that are listed below :

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

GenerationType.AUTO (default GenerationType)

The GenerationType.AUTO indicates that the persistence provider should select an appropriate strategy based on the specified database dialect. The AUTO will automatically set the generated values. All the databases support this strategy.

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

GenerationType.IDENTITY

The GenerationType.IDENTITY indicates that the persistence provider must assign primary keys for the entities using a database identity column. This strategy is not available in all the databases.

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

GenerationType.SEQUENCE

The GenerationType.SEQUENCE indicates that the persistence provider must assign primary keys for the entities using the database sequence. This strategy consists at defining a sequence name and use it in the classes. It is not supported by all the databases. A SEQUENCE GenerationType is global to the application; it can be accessed by one or more entities in the application.

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;

GenerationType.TABLE

The GenerationType.TABLE indicates that the persistence provider must assign primary keys for the entities using a database table. It uses a database table to store the latest primary key value. This strategy is available in all the databases.

@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private int id;

Laisser un commentaire