Jpa生成查询以从序列中获取nextval

时间:2014-05-26 09:15:32

标签: sql jpa

我需要使用jpa生成此查询

SELECT mysequence.NEXTVAL FROM DUAL. 

我有

entityManager.createNativeQuery("SELECT mysequence.NEXTVAL FROM DUAL").getFirstResult 

但它总是给出零并且从不递增序列本身。

3 个答案:

答案 0 :(得分:4)

您在查询对象上调用getFirstResult,这不是您的想法。请参阅Javadoc

尝试使用getSingleResult,这应该有效:

entityManager.createNativeQuery("SELECT mysequence.NEXTVAL FROM DUAL").getSingleResult();

答案 1 :(得分:0)

Hibernate 3.4 + Oracle 11

entityManager.createNativeQuery("SELECT mysequence.NEXTVAL FROM DUAL").getSingleResult();

生成以下sql

select * from ( select mysequence.nextval from dual ) where rownum <= 1

这是无效的sql,会导致 ORA-02287

在我看来,这仅适用于

entityManager.createNativeQuery("SELECT mysequence.NEXTVAL FROM DUAL").getResultList().get(0);

答案 2 :(得分:0)

try {
      Query query = getEntityManager().createNativeQuery("SELECT mysequence.NEXTVAL FROM DUAL");
        return (String) query.getSingleResult();
        //Query query = 
    } catch (Exception e) {
//handle exception here
}