Java.Hibernate.Beginner.What types of @GeneratedValue we have ?

The @GeneratedValue annotation lets you tell JPA/Hibernate how to automatically generate primary key values. You choose the strategy using strategy = GenerationType.XXX, where the main options are:


🔹 1️⃣ GenerationType.IDENTITY

  • Relies on the database’s auto-increment or identity columns.
  • The database generates the ID on insert.
  • Suitable for MySQL, SQL Server, PostgreSQL, etc.
  • No separate sequence or table needed.

Example:

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

🔹 2️⃣ GenerationType.SEQUENCE

  • Uses a database sequence object to generate unique IDs.
  • Portable across databases that support sequences (e.g., Oracle, PostgreSQL).
  • Typically more efficient than TABLE strategy.

Example:

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

🔹 3️⃣ GenerationType.TABLE

  • Uses a special table to store and increment primary key values.
  • Database-independent (works even on databases without sequences or identity columns).
  • Least efficient in high-concurrency environments → rarely used in modern projects.

Example:

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table_gen")
@TableGenerator(name = "user_table_gen", table = "id_generator", pkColumnName = "gen_name",
                valueColumnName = "gen_value", pkColumnValue = "user_id", allocationSize = 1)
private Long id;

🔹 4️⃣ GenerationType.AUTO

  • The default strategy: lets the JPA provider choose the best strategy based on the database dialect.
  • Might use IDENTITY, SEQUENCE, or TABLE depending on the DB.
  • Easiest way to let Hibernate handle key generation automatically.

Example:

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

🔹 Quick summary table:

StrategyHow it worksWhen to use
IDENTITYDatabase auto-incrementMySQL, SQL Server, etc.
SEQUENCEDatabase sequence objectOracle, PostgreSQL, etc.
TABLETable storing generated IDsDBs without sequences/identity
AUTOProvider picks best strategyWhen you want portability

You can choose among IDENTITY, SEQUENCE, TABLE, and AUTO in @GeneratedValue to control how Hibernate generates unique IDs — pick the one that fits your database and scalability needs.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.