Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting next value from sequence with jpa repository in postgreSQL

I've seen the similar question, but in my situation it doesn't work. I need to get the next value of the sequence.

Model class:

@Entity
@Table(name = "item")
public class Item {
    @Id
    @SequenceGenerator(name = "id_seq", sequenceName = "item_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_seq")
    @Column(name = "id", updatable = false)
    protected Long id;
}

Jpa Repository:

public interface ItemRepository extends JpaRepository<Item, Long> {
    List<Item> findFirst10ByOrderByPublicationDateDesc();

    @Query(value = "SELECT item_id_seq.nextval FROM item", nativeQuery = 
    true)
    Long getNextSeriesId();
}

I would appreciate any help.

like image 969
Geha Avatar asked Nov 25 '17 20:11

Geha


People also ask

What does findById return in JPA?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.

What is Nextval in Postgres?

Function. Description. nextval ( regclass ) → bigint. Advances the sequence object to its next value and returns that value. This is done atomically: even if multiple sessions execute nextval concurrently, each will safely receive a distinct sequence value.


1 Answers

I've found solution:

@Query(value = "SELECT nextval('item_id_seq')", nativeQuery =
            true)
    Long getNextSeriesId();

My mistake was that I used oracle syntax instead of postgreSQL, which I am using.

like image 200
Geha Avatar answered Sep 18 '22 15:09

Geha