The @GeneratedValue
marks a field as being generated by the database or programmatically upon insertion.
This annotation is typically applied to a field within a Java class that represents an entity in a data store.
It allows the specification of a generation strategy for the annotated field, indicating how the database generates
the values for this field.
The default generation strategy is {@link GenerationType#IDENTITY}.
-
strategy (Optional): Specifies the generation strategy for the annotated field. The default is GenerationType.IDENTITY
-
generator (Optional): Specifies the name of the generator to use (if applicable). The default is an empty string.
This generation method depends on the IdentityGenerator, which assumes that values are generated by an identity column in the database, typically through auto-incrementation. To employ this generation type, one only needs to configure the strategy parameter.
@Entity
public class User {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private long userId;
// ...
}
To utilize an id based on sequences, Bibernate offers the SequenceIdGenerator class. This generator utilizes sequences if they are supported by our database. To customize the sequence name, we can employ the @SequenceGenerator annotation with the specified sequence name.
@Entity
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id")
private Long id;
// ...
}
The generated values are unique for each sequence. If a sequence name is not specified, Bibernate will use sequence with name consisting of "tableName"_"columnName"_seq.