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 equal to @GeneratedValue(strategy=GenerationType.AUTO)
.
Still, as it is database–specific, it's the responsibility of the database to provide a value for this column, and the same rule is applied for @GeneratedValue(strategy...