Get Next Sequence Value from Database Using Hibernate

get next sequence value from database using hibernate

I found the solution:

public class DefaultPostgresKeyServer
{
private Session session;
private Iterator<BigInteger> iter;
private long batchSize;

public DefaultPostgresKeyServer (Session sess, long batchFetchSize)
{
this.session=sess;
batchSize = batchFetchSize;
iter = Collections.<BigInteger>emptyList().iterator();
}

@SuppressWarnings("unchecked")
public Long getNextKey()
{
if ( ! iter.hasNext() )
{
Query query = session.createSQLQuery( "SELECT nextval( 'mySchema.mySequence' ) FROM generate_series( 1, " + batchSize + " )" );

iter = (Iterator<BigInteger>) query.list().iterator();
}
return iter.next().longValue() ;
}

}

Getting Next value from sequence with spring hibernate

Finally I Solved my problem in the Spring way, All you need is to add a native query in the JpaRepository like this:

public interface EventRepository extends JpaRepository<Event, Long> {

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

Hibernate generates next sequence number by incrementing previous by 100

Thanks to this answer https://stackoverflow.com/a/31804619/9161059. Autoincrement adds 100 by default if Derby db was terminated. Here is an explanation of preallocator: https://db.apache.org/derby/docs/10.9/ref/rrefproperpreallocator.html

Query to get nextval from sequence with Spring JPA


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();

}

Hibernate picking up second previous id value for next sequence

According to your configuration, you're using a sequence to generate ids (test_data_seq) without using hibernate sequence value cache. As you set ID = 2000 manually, the sequence's current value isn't being updated. You need to update it manually, e.g. by using this function:

SELECT setval('test_data_seq', 2000);

In this case, the next generated value should be 2001.

Overall, it's better to avoid setting ids manually if you use sequence generators for it, because there is a high risk to have a collision.



Related Topics



Leave a reply



Submit