Skip to content

Latest commit

 

History

History
57 lines (40 loc) · 1.79 KB

GeneratedValue.md

File metadata and controls

57 lines (40 loc) · 1.79 KB

@GeneratedValue Annotation

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}.

Attributes

  1. strategy (Optional): Specifies the generation strategy for the annotated field. The default is GenerationType.IDENTITY

  2. generator (Optional): Specifies the name of the generator to use (if applicable). The default is an empty string.

Usage

IDENTITY Generation

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;

    // ...
}

SEQUENCE Generation

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.