0

I need to allocate a same unique id (batchid) for each row inserted in a BD during a batch execution as illustrated below.

| id | batchid |
| -- | ------- |
| 1  | 1       |
| 2  | 1       |
| 3  | 2       |
| 4  | 2       |
| 5  | 2       |
| 6  | 3       |

Was wondering if there is an automated way to do it with jpa annotation, like with a sequence ?

Hey StackExchange
  • 2,057
  • 3
  • 19
  • 35
  • You may query your database and get the next value from a sequence table, q.v. [this SO question](https://stackoverflow.com/questions/6386888/get-next-sequence-value-from-database-using-hibernate). One of the answers is even database agnostic. – Tim Biegeleisen Feb 07 '22 at 14:47

1 Answers1

0

Did it for now this way:

@Repository
public interface SeqRepository extends JpaRepository<CsvEntity, Long> {
    @Query(value = "SELECT nextval('batch_id_seq')", nativeQuery = true)
    Integer getNextBatchId();
}

schema.sql

CREATE SEQUENCE IF NOT EXISTS batch_id_seq
INCREMENT 1
START 1;
Hey StackExchange
  • 2,057
  • 3
  • 19
  • 35