4

My query method returns list of entities:

@Query("select u from ProfileDMO p inner join p.userPrincipal u where p.id=:profileId")
    List<UserPrincipalDMO> findUserPrincipalByProfileId(@Param("profileId") long profileId);

And I need only first result. Currently, I am using List.get(int index) to get first element.

Does anyone know how should I update my query method to return only first result?

2
  • 1
    Try this stackoverflow.com/a/35265491/5020294 Commented Dec 12, 2017 at 16:09
  • @AndriySlobodyanyk, thanks for response. That solution works for me. Commented Dec 13, 2017 at 15:26

1 Answer 1

9

Updated answer:

If you can't use a derived query where Spring Data JPA derives the query from the method name you can use a Pageable parameter to limit the results and a second method with a default implementation to hide the parameter and unwrap the result:

@Query("select u from ProfileDMO p inner join p.userPrincipal u where p.id=:profileId")
List<UserPrincipalDMO> internalFindUserPrincipalByProfileId(@Param("profileId") long profileId, Pageable page);

default UserPrincipalDMO findUserPrincipalByProfileId(long profileId){
    return internalFindUserPrincipalByProfileId(
        profileId, 
        PageRequest.of(0,1)
    ).get(0);
};

Of course, that leaves the internal implementation in your API, if you don't like that you always can fall back to a custom implementation.

Original answer:

You should be able to use query derivation, i.e. remove the @Query annotation and change your method to:

UserPrincipalDMO findFirstByUserPrincipalProfileId(@Param("profileId") long profileId);

If you don't like the name you can use a default method with your preferred name and delegate to the one I proposed.

If you don't want the method name at all in your interface you can provide a custom implementation.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your response. I couldn't use here query generation from method name approach, as UserPrincipalDMO entity doesn't have relation with ProfileDMO entity.
oh, I see the relation is the other way round. That leaves you with a custom implementation.
I updated my answer with a solution that is easier to implement.
should be PageRequest.of(0, 1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.