Hibernate custom primary key generation

Reference: https://www.cnblogs.com/xmqa/p/6424386.html

Hibernate customizes the primary key generation strategy and refers to the primary key generation strategy written by itself.

Note: The primary key generation strategy is implemented by writing a function yourself

When using Hibernate to define pojo, sometimes it is necessary to generate a certain regular data table primary key. At this time, we can use the custom primary key generation method to generate the primary key.

For example:

1. Define the primary key of the data table in the pojo attribute

@Id
@GenericGenerator(name = "xmqId", strategy = "com.xmq.core.XMQGenerator")  //定义一个主键生成器,并给该生成器命名,该生成器指定策略为一个类
@GeneratedValue(generator = "xmqId")  //通过名称引用我们自定义的那个主键生成器
@Column(name = "C_ID")
private String pk;

2. Create a primary key generator

package com.xmq.core;

import java.io.Serializable;

import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.UUIDHexGenerator;

public class XMQGenerator extends UUIDHexGenerator {

    public XMQGenerator () {
        super();
    }

    @Override
    public Serializable generate(SessionImplementor session, Object obj) {
        return "PK_" + super.generate(session, obj);
    }


}

Note: @MappedSuperclass is sometimes annotated in the parent class of pojo, which means that the parent class is not a complete entity class and will not be mapped to a database table, but its attributes will be mapped to the data table of its subclasses field.

Guess you like

Origin blog.csdn.net/banzhengyu/article/details/122248641