Hibernate从数据库函数生成ID

时间:2014-03-18 12:49:06

标签: java hibernate

我的代码是

    `@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)

所以请告诉我该怎么做..

1 个答案:

答案 0 :(得分:6)

您可以使用自定义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的自定义生成器,并将实体的属性作为存储的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;
  }
}