Home > Back-end >  Generate Custom Id in JPA with different initial value
Generate Custom Id in JPA with different initial value

Time:09-06

I have been following Thorben's blog (Custom String Prefix Sequence generator) to generate custom ID of type String prefix followed by number . My requirement is to generate custom ids like

CUS-60000

CUS-60005

CUS-60010

  • How do we set a different initial value . Following the blog , it always starts from 1 and produces value CUS-000001
  • How INCREMENT_PARAM works. Even setting this value to 5 , my next id is incremented by 1. Values generated are CUS-000002,CUS-000003

Entity class

@Entity
@Table(name = "test")
@Data
public class Test  {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "test_seq")
    @GenericGenerator(name = "test_seq", strategy = "com.xxx.entity.StringPrefixedSequenceIdGenerator", parameters = {
            @Parameter(name = StringPrefixedSequenceIdGenerator.VALUE_PREFIX_PARAMETER, value = "CUS-"),
            @Parameter(name = StringPrefixedSequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "d")})
    @Column(name = "id", updatable = false, nullable = false)
    private String id;

    private String name;

}

Custom Sequence Generator class

public class StringPrefixedSequenceIdGenerator extends SequenceStyleGenerator {

    public static final String VALUE_PREFIX_PARAMETER = "valuePrefix";
    public static final String VALUE_PREFIX_DEFAULT = "";
    private String valuePrefix;

    public static final String NUMBER_FORMAT_PARAMETER = "numberFormat";
    public static final String NUMBER_FORMAT_DEFAULT = "%d";
    private String numberFormat;

    @Override
    public Serializable generate(SharedSessionContractImplementor session,
            Object object) throws HibernateException {
        return valuePrefix
                  String.format(numberFormat, super.generate(session, object));
    }

    @Override
    public void configure(Type type, Properties params,
            ServiceRegistry serviceRegistry) throws MappingException {
        super.configure(LongType.INSTANCE, params, serviceRegistry);
        valuePrefix = ConfigurationHelper.getString(VALUE_PREFIX_PARAMETER,
                params, VALUE_PREFIX_DEFAULT);
        numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER,
                params, NUMBER_FORMAT_DEFAULT);
    }

}

CodePudding user response:

Add the following parameters to @GenericGenerator which should start your sequence at 5 and increment by 5. This will get the next value in the sequence for each entity persisted

    @Parameter(name = StringPrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "5"),
    @Parameter(name = StringPrefixedSequenceIdGenerator.INITIAL_PARAM, value = "5"),
    @Parameter(name = "optimizer", value = "pooled-hi"),

The sequence of ids from the customer sequence generator should be

CUS-00005
CUS-00010
CUS-00015
...
  • Related