我的代码是
`@Id
@GenericGenerator(name="generator", strategy="increment")
@GeneratedValue(generator="generator")
@Column(name = "PM_ID", nullable = false, length=12)
private long pmId;`
Run Code Online (Sandbox Code Playgroud)
在上面,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 ....
Run Code Online (Sandbox Code Playgroud)
并创建您的自定义生成器实现IdentifierGenerator和传递您的实体的属性作为存储的proc参数:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1771 次 |
| 最近记录: |