在 SAP Hana 中插入时获取自动增量 ID

Getting autoincrement id on insert in SAP Hana

我有一个带有自动增量列的 table,如 here

所述

Java/Hibernate中是这样定义的:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int ID;

这是在 CREATE TABLE 中定义列的方式(注意,无顺序):

"ID" INTEGER CS_INT GENERATED BY DEFAULT AS IDENTITY

现在,我想在 table 中插入一行并检索生成的 ID。问题是驱动程序不支持 Statement.RETURN_GENERATED_KEYS 使用 fetch 语句检索 id。

另一方面,由于我没有创建序列,所以无法使用 nextval。关于如何获取自动递增的 ID 有什么想法吗?

注意: JDBC 有类似的问题,它不是特定于 Hibernate 的。

更新

示例代码(在Java/Hibernate中):

        val c = new MyJpaClass
        c.code = 1
        c.name = "abc"
        c.version = 0
        entityManger.getTransaction.begin
        entityManger.persist(c)
        entityManger.getTransaction.commit

        // c.id should be populated here with the assigned autoincremented id

当您持久保存实体时,Hibernate 会在提交事务时将其与数据库同步。所以,你可以简单地做 c.getId();

更新 这里是单元测试的例子。所有文件都是 here

import static org.junit.Assert.assertNotNull;

import java.io.FileNotFoundException;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class PersistTest {
    Logger LOG = LogManager.getLogger(PersistTest.class);

protected static EntityManagerFactory emf;
protected static EntityManager em;

@BeforeClass
public static void init() throws FileNotFoundException, SQLException {
    emf = Persistence.createEntityManagerFactory("HelloWorldPU");
    em = emf.createEntityManager();
}

@AfterClass
public static void tearDown(){
    em.clear();
    em.close();
    emf.close();
}

@Test
public void testPersist_success() {
    em.getTransaction().begin();
    MyJpaClass o = new MyJpaClass();
    o.setMessage("text");
    em.persist(o);
    em.getTransaction().commit();

    assertNotNull(o.getId());
    LOG.debug(o.getId());
}

}