我的代码是
`@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 列,并希望将值传递给该函数。
我的函数名称是generateD(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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)