Creating an autogenerator column

Generally, we create a primary column with some autogenerated value. Hibernate allows us to create the same using code. Let's take a look at some methods to create a column with an autogenerated value.

How to do it…

We can create an autogenerated column in many ways, such as:

  • Using a default generation strategy
  • Using a sequence generator
  • Using a table generator

Default generation strategy

To use a default strategy for autogeneration, we will use the @GeneratedValue annotation, as follows:

@Id
@GeneratedValue
private long id;

Using the preceding code, hibernate will create a column with an autoincremental value.

By default, hibernate uses the GenerationType.AUTO strategy if no strategy is supplied; so, @GeneratedValue is ...

Get Java Hibernate Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.