有没有一种方法可以使用带前缀的@GeneratedValue创建字符串序列?

时间:2019-04-09 07:43:43

标签: java hibernate spring-boot

我想创建一个前缀为“ CID_00001”的序列(例如):

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)   
private String id;

有什么办法吗?

2 个答案:

答案 0 :(得分:1)

我认为您正在使用数据库序列来生成PK。因此,在插入表之前添加触发器。例如,(在oracle中)

CREATE OR REPLACE TRIGGER sometable_trigger  
BEFORE INSERT ON SomeTable
FOR EACH ROW

BEGIN
  SELECT 'CID_' || to_char(sometable_seq.NEXTVAL, "00009")
  INTO   :new.id
  FROM   dual;
END;
/

假设:序列名称为“ sometable_seq ”,id列名称为id

答案 1 :(得分:1)

您可以使用custom id generator来做到这一点。

最简单的方法是扩展Hibernate的SequenceStyleGenerator,它实现对数据库序列的访问(包括一些有趣的优化)

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

实现自己的ID生成器后,可以在@GenericGenerator批注中引用它。

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_seq")
    @GenericGenerator(
        name = "book_seq", 
        strategy = "org.thoughts.on.java.generators.StringPrefixedSequenceIdGenerator", 
        parameters = {
            @Parameter(name = StringPrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "50"),
            @Parameter(name = StringPrefixedSequenceIdGenerator.VALUE_PREFIX_PARAMETER, value = "CID_"),
            @Parameter(name = StringPrefixedSequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%05d") })
    private String id;

    ...
}