Home > other >  Spring JPA select single column with count limit
Spring JPA select single column with count limit

Time:06-14

I want to fetch id from my table with count limit=1.

What I tried?

Optional<Long> findFirstIdByServiceSeeker_Id(Long serviceSeekerId); // But it returns Entity. I need id alone

I have following solution to fix it, but I want to know how to fetch id along with limit?

Alternate solution:

 Optional<User> findFirstIdByServiceSeeker_Id(Long serviceSeekerId); 
 Optional<User> userOptional =  userRepository.findFirstIdByServiceSeeker_Id(serviceSeekerId);
 Long userId =userOptional.get().getId();// it will fix

CodePudding user response:

in jpa u can make it as follow ,

Optional<CustomType> findFirstIdByServiceSeeker_Id(Long serviceSeekerId);




public interface CustomType {
    getId();
    }

CodePudding user response:

Try writing custom Query like this! (Modify as per the DB/SQL Conventions)

@Query("SELECT serviceSeekerId from USERS u where u.serviceSeekerId= :serviceSeekerId")

Long findFirstIdByServiceSeekerId(String id);

Refer similar links

https://www.baeldung.com/spring-data-jpa-query

Creating a custom query with Spring DATA JPA?

  • Related