gpt4 book ai didi

java - hibernate中自定义Long类型ID生成

转载 作者:行者123 更新时间:2023-12-02 10:46:53 27 4
gpt4 key购买 nike

有没有办法在hibernate中生成长类型的自定义id作为主键?我读过这篇hibernate ID但当 Id 类型为 String 时,它可以工作。我想要的 id 看起来像“yyyymm00001”,例如:20180900001;下面的方法返回我想要的格式,但是是字符串类型。我怎样才能把它变成长类型?

@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
Serializable result = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;


String year= String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
String month= String.format("%02d",Calendar.getInstance().get(Calendar.MONTH)+1);
try {
connection = session.connection();
statement = connection.createStatement();
try {

statement.executeUpdate("UPDATE " + DEFAULT_SEQUENCE_NAME + " SET next_val=LAST_INSERT_ID(next_val+1)");
resultSet = statement.executeQuery("SELECT next_val FROM " + DEFAULT_SEQUENCE_NAME);
} catch (Exception e) {

System.out.println("In catch, cause : Table is not available.");

statement.executeUpdate("UPDATE " + DEFAULT_SEQUENCE_NAME + " SET next_val=LAST_INSERT_ID(next_val+1)");
resultSet = statement.executeQuery("SELECT next_val FROM " + DEFAULT_SEQUENCE_NAME);

}
if (resultSet.next()) {

int nextValue = resultSet.getInt(1);
String suffix = String.format("%05d", nextValue);
result = year.concat(month).concat(suffix);
System.out.println("Custom generated sequence is : " + result);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}

最佳答案

要解决此问题,您必须在实体中添加此注释并为 @Id 设置 Long 或 Integer 类型

@Id
@Column(name = Contact.ENCOIDFSYS)
@GeneratedValue(generator = IdfsysGeneratorDefinition.NAME)
@GenericGenerator(name = IdfsysGeneratorDefinition.NAME, strategy = IdfsysGeneratorDefinition.CLASS_NAME, parameters = { })
private Integer id;

知道

public static final String CLASS_NAME = "com.sybaway.generators.hibernate.HibernateIdfsysGenerator";
public static final String NAME = "idfsysGenerator";

并在 hibernate 生成器类中,将此转换添加到 Long

result = Long.parseLong(year.concat(month).concat(suffix));

而不是:

result = year.concat(month).concat(suffix);

如果一切顺利请告诉我

关于java - hibernate中自定义Long类型ID生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52477140/

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