Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDSL Paging Sorting duplicates

I have got an Entity A say Car with a OneToMany relationship to an Entity B say CarProperty.

My Car Repository extends QueryDslPredicateExecutor to support paging and sorting:

Page<T> findAll(Predicate predicate, Pageable pageable);

I'm trying to execute a query where I sort the results, by a column of CarProperty, defining the sort on pageable variable. However since it is a One To Many relationship between Car and CarProperty, I have returned duplicates of Car. Is it possible to obtain distinct results on Car using this structure?

If it is not possible to use distinct on the Predicate, how could I represent the following query in the predicate (using exists to eliminate duplicates):

SELECT Car.*
FROM Car C LEFT JOIN CarProperty CP ON (C.ID = CP.CAR_ID)
WHERE EXISTS (SELECT 1 
              FROM CarProperty CP2
              WHERE CP2.CAR_ID = C.ID AND CP2.ID = CP.ID)
ORDER BY CP.PROPERTY_NAME ASC;

Thanks in advance

like image 331
Aderito Baptista Avatar asked Jul 20 '26 19:07

Aderito Baptista


1 Answers

You can use named entity graph to avoid duplicate records, in my case it worked.

    @NamedEntityGraph(name = "Car.carProperty" ,attributeNodes = @NamedAttributeNode("carProperties"))
    @Entity
    public class Car {
        @OneToMany
        @JoinColumn(name = "carProperties")
        private List<CarProperty> carProperties;
    }

and then override findall method

@EntityGraph(value = "Car.carProperty" , type = EntityGraphType.LOAD)
Page<Car> findAll(Predicate predicate, Pageable pageable);
like image 171
Ashish Bakwad Avatar answered Jul 25 '26 05:07

Ashish Bakwad