Tarmizi Hamid
Tarmizi Hamid

Reputation: 103

Using Custom Id Generator Hibernate JPA?

I have a Generator Class to generate custom id in hibernate using jpa annotation, my generator class like below:

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();
    }    
}

I want to use it in my entity, I write it like below:

@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;

}

Not work for me, here is my refference https://www.onlinetutorialspoint.com/hibernate/custom-generator-class-in-hibernate.html#comment-58952

Upvotes: 4

Views: 6222

Answers (1)

Ehab Qadah
Ehab Qadah

Reputation: 570

you can improve the ID generator for example by extending the org.hibernate.id.UUIDGenerator like this:

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);
    }
}

and use it like this:

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

Upvotes: 3

Related Questions