Defining a primary key using the @Id
and @GeneratedValue
annotations in Hibernate (or JPA) is straightforward and commonly used to automate primary key generation for database entities. Here’s a guide:
Steps:
- Use
@Id
annotation: Marks a field in your entity class as the primary key. - Use
@GeneratedValue
annotation: Specifies that the primary key values should be automatically generated. You can customize the generation strategy using thestrategy
attribute. - Optional Generation Strategies: Hibernate/JPA provides several strategies:
GenerationType.IDENTITY
– Relies on the database to auto-generate the key (common for auto-increment columns).GenerationType.SEQUENCE
– Uses a sequence in the database.GenerationType.TABLE
– Uses a table for primary key generation.GenerationType.AUTO
– Allows Hibernate to choose the best strategy based on the database dialect.
Example Code:
Here’s an example of a simple entity with an auto-generated primary key:
package org.kodejava.hibernate;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Explanation:
@Entity
: Marks this class as a JPA entity.@Id
: Specifies theid
field as the primary key.@GeneratedValue(strategy = GenerationType.IDENTITY)
: Configures the primary key to use theIDENTITY
generation strategy, which relies on database auto-increment.
Generation Strategies in Detail:
GenerationType.IDENTITY
:- Directly uses the database’s auto-increment column.
- Simple and efficient for most databases.
GenerationType.SEQUENCE
:- Suitable for databases with sequence support (e.g., PostgreSQL, Oracle).
- Example:
@GeneratedValue(strategy = GenerationType.SEQUENCE)
GenerationType.TABLE
:- Uses a database table to generate unique IDs (less common).
- Example:
@GeneratedValue(strategy = GenerationType.TABLE)
GenerationType.AUTO
:- Lets Hibernate pick an appropriate strategy based on the database dialect.
Notes:
- Ensure that proper database configurations (e.g., database schema, auto-increment, or sequences) align with the chosen generation strategy.
- Hibernate will handle primary key generation and insertion automatically when persisting entities with
EntityManager
orSession
.