4
votes

I have a repository with which I am trying to get next value from sequence. The sequence name I need to be parameterized.

The repository query looks a like:

@Query(value = "SELECT ?1.NEXTVAL from dual;", nativeQuery = true) String getSeqID(@Param("seqName") String seqName);

But, I am getting following exception:

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
Why do you needed nextval from sequence?Peter Šály
This is a functional need and the nextval from the sequence is required to be retrieved so the it can be used as a employee code.Ashish Chauhan

4 Answers

4
votes
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
votes
@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();

EDIT:

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

You can use EntityManager:

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

In PostgreSQL it is:

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