2020-04-21

Hibernate JPA @TableGenerator Example

@TableGenerator

The @TableGenerator annotation is used to specify the database table used by the identity generator of the currently annotated entity.

TableGenerator Defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation. A table 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 1:
   
    @Entity public class Employee {
        ...
        @TableGenerator(
            name="empGen",
            table="ID_GEN",
            pkColumnName="GEN_KEY",
            valueColumnName="GEN_VALUE",
            pkColumnValue="EMP_ID",
            allocationSize=1)
        @Id
        @GeneratedValue(strategy=TABLE, generator="empGen")
        int id;
        ...
    }
   
    Example 2:
   
    @Entity public class Address {
        ...
        @TableGenerator(
            name="addressGen",
            table="ID_GEN",
            pkColumnName="GEN_KEY",
            valueColumnName="GEN_VALUE",
            pkColumnValue="ADDR_ID")
        @Id
        @GeneratedValue(strategy=TABLE, generator="addressGen")
        int id;
        ...
    }

Configured table generator

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

@Id
@GeneratedValue(
strategy = GenerationType.TABLE,
generator = "table-generator"
)
@TableGenerator(
name =  "table-generator",
table = "table_identifier",
pkColumnName = "table_name",
valueColumnName = "product_id",
allocationSize = 5
)
private Long id;

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

//Getters and setters are omitted for brevity

No comments:

Post a Comment