Search code examples
jpamappingmulti-selectpojo

JPA avoid List<Obect[]> when selecting multiple entites


In my repository I have a query that looks like this:

 @Query("select us,ul FROM UserScore us LEFT JOIN us.userLike ul WHERE us.param1=:param1 and ul.param2=:param2)
    public List<Object[]> getTest(@Param("param1") Integer param1, @Param("param2") Integer param2);

Is there a way to avoid returning List and instead returning something like this List ?

@Entity
public UserScoreUserLike {
     private UserScore userScore;
     private UserLike userLike
[getters setters]
}

In a way, making JPA mapped the result of the multi select with my custom Entity/POJO?

Thank you!


Solution

  • The "select new" notation is your friend, where you're selecting the creation of a wrapper object. So your JPA query would look something like

    select new UserScoreUserLike(us, ul) from UserScore ...
    

    Note that your wrapper object doesn't have to be (and maybe shouldn't be) and entity object.

    See this other StackOverflow answer: JPQL Create new Object In Select Statement - avoid or embrace?