I am using Spring JPA and Hibernate to build a REST API. I am searching for 2 days, but i didn't find any solution to fix this issue.
In some queries i have multiple JOIN FETCH clauses. When I execute my query i have the parent object multiple times in my result set, in fact exactly as often as the father has children.
Example:
@Query("SELECT DISTINCT p AS post," +
" <some subquery>" +
"FROM Post p JOIN FETCH p.user u LEFT JOIN FETCH p.linkedUsers INNER JOIN FETCH p.track track "
"WHERE ( (<some condition>) OR p.user = :me) " +
"ORDER BY p.created DESC")
List<Object []> getData(@Param("me")User me,
Pageable pageable);
For example if i have a post with 2 linked users my post will appear at least 2 times in my result set. If i don't do the JOIN FETCH or an other JOIN the data is loaded lazily. But this is not a goal for me since it causes a bad performance.
Edit: So my question is, how to execute one query where all data is fetched and all posts which met the specified criteria are only ONE time in my resultset.
Edit:
Example object is:
[{
"id": 1767,
"track": {
"id": 1766,
"title": "VVS",
...
"streams": [
{
"id": 1764,
....
},
{
"id": 1765,
...
}
],
"isrc": "DEQ021801393"
},
"user": {
"id": 999998,
"username": "My username",
....
},
"created": "2018-08-21T22:18:56.451Z",
...
"linked_users": []
},
<this object another time, beacause two stream objects in track>
<many other objects two times>
...
]
Edit:
It turned out, that the subqueries stand in conflict with the "distinct". If i remove them from the query i get distinct posts. If i edit the native sql query and alter the "distinct" to a "distinct on" it works. But i think a "distinct on" clause doesn't exist in hibernate. So any good ideas what to do?
I would appreciate any help :)