gpt4 book ai didi

spring - 如何在 JPA 中生成自定义 Id

转载 作者:行者123 更新时间:2023-12-03 03:36:56 25 4
gpt4 key购买 nike

我想在 JPA 中生成自定义 ID,它必须是表的主键。有很多使用 hibernate 创建自定义 Id 的示例,例如 this我想要相同的实现,但在 JPA 中。ID 必须是字母数字,如 STAND0001

谢谢。

最佳答案

您可以使用 GenericGenerator 来完成此操作,如下所示:

 @Entity
public class Client {

@Id
@GenericGenerator(name = "client_id", strategy = "com.eframe.model.generator.ClientIdGenerator")
@GeneratedValue(generator = "client_id")
@Column(name="client_id")
private String clientId;
}

和自定义生成器类(将为ID添加前缀,你可以让它做你喜欢的事情):

public class ClientIdGenerator implements IdentifierGenerator {

@Override
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {

String prefix = "cli";
Connection connection = session.connection();

try {
Statement statement=connection.createStatement();

ResultSet rs=statement.executeQuery("select count(client_id) as Id from Client");

if(rs.next())
{
int id=rs.getInt(1)+101;
String generatedId = prefix + new Integer(id).toString();
return generatedId;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}
}

关于spring - 如何在 JPA 中生成自定义 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259048/

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