gpt4 book ai didi

java - 有没有办法使用带有前缀的 @GenerateValue 创建字符串序列?

转载 作者:行者123 更新时间:2023-12-01 17:45:41 26 4
gpt4 key购买 nike

我想创建一个带有前缀“CID_00001”的序列(示例):

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

有什么办法可以做到这一点吗?

最佳答案

您可以使用 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;

...
}

关于java - 有没有办法使用带有前缀的 @GenerateValue 创建字符串序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55587520/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com