我有一个带有自动递增列的表,如here
所述这是在Java / Hibernate中的定义方式:
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int ID;
这是在CREATE TABLE中定义列的方式(注意,无序列):
"ID" INTEGER CS_INT GENERATED BY DEFAULT AS IDENTITY
现在,我想在表中插入一行并检索结果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
答案 0 :(得分:0)
当持久化实体时,在提交事务时,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());
}
}