How do I define a primary key with @Id and @GeneratedValue in Hibernate?

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:

  1. Use @Id annotation: Marks a field in your entity class as the primary key.
  2. Use @GeneratedValue annotation: Specifies that the primary key values should be automatically generated. You can customize the generation strategy using the strategy attribute.
  3. 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 the id field as the primary key.
  • @GeneratedValue(strategy = GenerationType.IDENTITY): Configures the primary key to use the IDENTITY generation strategy, which relies on database auto-increment.

Generation Strategies in Detail:

  1. GenerationType.IDENTITY:
    • Directly uses the database’s auto-increment column.
    • Simple and efficient for most databases.
  2. GenerationType.SEQUENCE:
    • Suitable for databases with sequence support (e.g., PostgreSQL, Oracle).
    • Example:
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    
  3. GenerationType.TABLE:
    • Uses a database table to generate unique IDs (less common).
    • Example:
    @GeneratedValue(strategy = GenerationType.TABLE)
    
  4. 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 or Session.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.