使用自定义ID生成器Hibernate JPA?

时间:2018-08-06 06:30:16

标签: java hibernate spring-mvc jpa

我有一个生成器类,可以使用jpa注释在休眠状态下生成自定义ID,我的生成器类如下:

public class PolIdGenerator implements  IdentifierGenerator {

    public int generatePolId() {
        Random random = new Random();
        return random.nextInt(100);
    }

    @Override
    public Serializable generate(SessionImplementor si, Object o) throws HibernateException {
        return "POL" + this.generatePolId();
    }    
}

我想在我的实体中使用它,如下所示:

@Entity
@Table(name="POLI")
public class Poli extends DefaultEntityImpl implements Serializable{

    @GeneratedValue(generator = "polIdGenerator")
    @GenericGenerator(name = "polIdGenerator", 
        parameters = @Parameter(name = "prefix", value = "pol"),
        strategy = "id.rekam.medis.generator.PolIdGenerator")
    @Id    
    @Column(name = "ID")
    private String id;

}

不适用于我,这是我的推荐https://www.onlinetutorialspoint.com/hibernate/custom-generator-class-in-hibernate.html#comment-58952

1 个答案:

答案 0 :(得分:0)

例如,您可以通过扩展org.hibernate.id.UUIDGenerator来改善ID生成器,例如:

package com.project.generator;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.UUIDGenerator;

import java.io.Serializable;
import java.util.Objects;
import java.util.Random;

/**
 * A custom Id generator based on combination of long time hex string and UUID
 *
 * @author Ehab Qadah
 */
public class CustomIdentifierGenerator extends UUIDGenerator {

    private static final int NUMBER_OF_CHARS_IN_ID_PART = -4;

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
        final String uuid = super.generate(session, obj).toString();
        final long longTimeRandom = System.nanoTime() + System.currentTimeMillis() + new Random().nextLong() + Objects.hash(obj);
        final String timeHex = Long.toHexString(longTimeRandom);
        return "POL"+ StringUtils.substring(timeHex, NUMBER_OF_CHARS_IN_ID_PART) + StringUtils.substring(uuid, NUMBER_OF_CHARS_IN_ID_PART);
    }
}

并像这样使用它:

    @Id
    @GeneratedValue(generator = "custom-generator", strategy = GenerationType.IDENTITY)
    @GenericGenerator(name = "custom-generator", strategy = "com.project.CustomIdentifierGenerator")
    protected String id;