使用Spring JPA查询从序列中获取nextval

时间:2019-03-05 15:28:01

标签: java spring hibernate jpa spring-data-jpa

我有一个存储库,我正在尝试从序列中获取下一个值。我需要对序列名称进行参数化。

存储库查询类似于:

  

@Query(值=“从double;中选择SELECT?1.NEXTVAL”; nativeQuery = true)   字符串getSeqID(@Param(“ seqName”)字符串seqName);

但是,我遇到以下异常:

org.hibernate.QueryException: JPA-style positional param was not an integral ordinal
    at org.hibernate.engine.query.spi.ParameterParser.parse(ParameterParser.java:187) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.query.spi.ParamLocationRecognizer.parseLocations(ParamLocationRecognizer.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.query.internal.NativeQueryInterpreterStandardImpl.getParameterMetadata(NativeQueryInterpreterStandardImpl.java:34) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.query.spi.QueryPlanCache.getSQLParameterMetadata(QueryPlanCache.java:125) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]

4 个答案:

答案 0 :(得分:1)

您可以使用EntityManager

entityManager.createNativeQuery("select seqname.nextval ...").getSingleResult();

答案 1 :(得分:1)

package br.com.mypackage.projectname.repository;

import java.math.BigDecimal;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface MyRepository extends JpaRepository<Myentity, Long> {

    @Query(value = "SELECT SCHEMA.SEQUENCE_NAME.nextval FROM dual", nativeQuery = true)
    public BigDecimal getNextValMySequence();

}

答案 2 :(得分:0)

@Entity
@Table(name = "tabelName")
public class yourEntity{
    @Id
    @SequenceGenerator(name = "yourName", sequenceName = "yourSeqName", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "yourName")
    @Column(name = "id", updatable = false)
    protected Long id;
}

@Query(value = "SELECT yourSeqName.nextval FROM tableName", nativeQuery = true)
Long getNextSeriesId();

编辑:

Query q = em.createNativeQuery("SELECT yourSeqName.NEXTVAL FROM DUAL");
return (java.math.BigDecimal)q.getSingleResult();

答案 3 :(得分:0)

在PostgreSQL中是:

Long value = Long.parseLong(entityManager
            .createNativeQuery("select nextval('sequence_name')")
            .getSingleResult().toString());