gpt4 book ai didi

java - Hibernate 从数据库函数生成 ID

转载 作者:搜寻专家 更新时间:2023-11-01 02:09:04 25 4
gpt4 key购买 nike

我的代码是

    `@Id
@GenericGenerator(name="generator", strategy="increment")
@GeneratedValue(generator="generator")

@Column(name = "PM_ID", nullable = false, length=12)
private long pmId;`

上面的id是由数据库中的max id +1生成的但我想从数据库函数生成这个 pmid 列,并想将值传递给该函数。我的函数名称是 generateID(2,3)

所以请告诉我如何做到这一点..

最佳答案

您可以使用自定义 ID 生成器来调用您的存储过程。

将您的 @Id 定义为指向您的自定义生成器:

@Id
@GenericGenerator(name="MyCustomGenerator", strategy="org.mytest.entity.CustomIdGenerator" )
@GeneratedValue(generator="MyCustomGenerator" )
@Column(name = "PM_ID", nullable = false, length=12)
private long pmId;

private Integer field1;

private Integer field2;

.... your getters and setters ....

并创建您的自定义生成器,实现 IdentifierGenerator 并将您的实体的属性作为存储过程参数传递:

public class CustomIdGenerator implements IdentifierGenerator {

private static final String QUERY_CALL_STORE_PROC = "call generateId(?,?,?)";

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

Long result = null;
try {
Connection connection = session.connection();
CallableStatement callableStmt = connection. prepareCall(QUERY_CALL_STORE_PROC);
callableStmt.registerOutParameter(1, java.sql.Types.BIGINT);
callableStmt.setInt(2, ((MyObject) object).getField1());
callableStmt.setInt(3, ((MyObject) object).getField2());
callableStmt.executeQuery();
// get result from out parameter #1
result = callableStmt.getLong(1);
connection.close();
} catch (SQLException sqlException) {
throw new HibernateException(sqlException);
}
return result;
}
}

关于java - Hibernate 从数据库函数生成 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22479912/

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