Ladu anand
Ladu anand

Reputation: 650

Generate Custom Id in JPA with different initial value

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

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 = "%05d")})
    @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);
    }

}

Upvotes: 0

Views: 1167

Answers (1)

johnnyutts
johnnyutts

Reputation: 1452

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
...

Upvotes: 1

Related Questions