'How can I get a sequence number from an oracle database with jpaRepository?

I´m trying to get a sequence number from an oracle database using a jpaRepository.

The main problem is because I don´t have any Object in JpaRepository so I don´t really know how to solve it. The sequence number will be a Long, and I only need to return this number in my repository.

My code:

@Repository
public interface InsuranceRepository extends JpaRepository<Long, Long> {

    @Query(value = "SELECT INSURANCE_VOUCHER_SEQ.nextval FROM dual", nativeQuery = true)
    Long findInsuranceVoucher();
}

I know is wrong, but I don´t know how I should implement it.

Thanks everyone.



Solution 1:[1]

You could theoretically do it, but it will be ugly. How about using @PersistenceContext like so:

@Repository
public class InsuranceDao {

    @PersistenceContext
    private EntityManager entityManager;
    
    public Long getInsuranceVoucher() {
        Query q = entityManager.createNativeQuery("SELECT INSURANCE_VOUCHER_SEQ.nextval FROM dual");
        
        return (Long) q.getSingleResult();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jumping_monkey