Loading

JPA使用GenerationType.TABLE生成主键

1、新建保存每张表最新主键的 主键表

clipboard

 

2、修改实体类上的主键生成策略

//进行映射的表的名称
@Entity
public class Customer {

    private Integer id;
    private String lastName;

    private String email;
    private int age;
    private Date createdTime;
    private Date birth;
    
    

    //生成主键的方式
    @TableGenerator(name="ID_GENERATOR", //name 属性表示该主键生成策略的名称,它被引用在@GeneratedValue中设置的generator 值中
            table="JPA_ID_GENERATOR",//table 属性表示表生成策略所持久化的表名
            pkColumnName="PK_NAME",//表示在持久化表中,该主键生成策略所对应键值的名称
            pkColumnValue="CUSTOMER_ID", // CUSTOMER_ID 对应的 PK_VALUE存储的就是 Customer表最新的一条数据的主键
            valueColumnName="PK_VALUE",//持久化表中,该主键当前所生成的值,它的值将会随着每次创建累加
            allocationSize=50)
    /*@GeneratedValue(strategy=GenerationType.AUTO)*/
    @Id
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name="LAST_NAME",length=255,nullable=false)
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Column(name="EMAIL",length=50,nullable=false)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name="AGE")
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    // 创建时间精确到时间戳
    @Column(name="CREATED_TIME")
    @Temporal(TemporalType.TIMESTAMP)
    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    //生日则精确到天
    @Column(name="BIRTH")
    @Temporal(TemporalType.DATE)
    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "Customer [id=" + id + ", lastName=" + lastName + ", email=" + email + ", age=" + age + ", createdTime="
                + createdTime + ", birth=" + birth + "]";
    }
    
    
}

 

clipboard

 

3、测试

1) 查看控制台打印

//每次向业务表插入数据时,去主键表查询该业务表的主键
Hibernate: 
    select
        PK_VALUE 
    from
        JPA_ID_GENERATOR 
    where
        PK_NAME = 'CUSTOMER_ID' for update  
          
Hibernate: 
    insert 
    into
        JPA_ID_GENERATOR
        (PK_NAME, PK_VALUE) 
    values
        ('CUSTOMER_ID', ?)
Hibernate: 
    update
        JPA_ID_GENERATOR 
    set
        PK_VALUE = ? 
    where
        PK_VALUE = ? 
        and PK_NAME = 'CUSTOMER_ID'
Hibernate: 
    insert 
    into
        Customer
        (AGE, BIRTH, CREATED_TIME, EMAIL, LAST_NAME, id) 
    values
        (?, ?, ?, ?, ?, ?)

 

clipboard

posted @ 2020-07-12 23:39  青岑  阅读(1066)  评论(0编辑  收藏  举报