2020-04-21

Hibernate JPA @SequenceGenerator Example

@SequenceGenerator

The @SequenceGenerator annotation is used to specify the database sequence used by the identifier generator of the currently annotated entity.

SequenceGenerator Defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation. A sequence generator may be specified on the entity class or on the primary key field or property. The scope of the generator name is global to the persistence unit (across all generator types).

   Example:

   @SequenceGenerator(name="EMP_SEQ", allocationSize=25)

Example : Named sequence

@Entity(name = "Product")
public static class Product {

@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "sequence-generator"
)
@SequenceGenerator(
name = "sequence-generator",
sequenceName = "product_sequence"
)
private Long id;

@Column(name = "product_name")
private String name;

//Getters and setters are omitted for brevity

}

Example: Configured sequence

@Entity(name = "Product")
public static class Product {

@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "sequence-generator"
)
@SequenceGenerator(
name = "sequence-generator",
sequenceName = "product_sequence",
allocationSize = 5
)
private Long id;

@Column(name = "product_name")
private String name;

//Getters and setters are omitted for brevity

}

No comments:

Post a Comment