Hibernate从数据库函数生成ID

6

我的代码是

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

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

以上的id是通过从数据库中获取的最大id加1生成的,但我希望能够从数据库函数中生成pmid列,并将值传递给该函数。我的函数名称是generateID(2,3)。

请告诉我如何实现这一点。

1个回答

7
你可以使用自定义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;
  }
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接