speedment / jpa-streamer

JPAstreamer is a lightweight library for expressing JPA queries as Java Streams
GNU Lesser General Public License v2.1
339 stars 35 forks source link

Merger applies all limit()-operators #353

Closed julgus closed 1 year ago

julgus commented 1 year ago

Describe the bug Limit is applied to the wrong Entities when using .flatMap().

Expected behavior The following two streams should generate the same list of films:

 List<String> expectedFilms = languages.stream()
                .sorted(Comparator.comparing(Language::getName))
                .flatMap(l -> l.getFilms().stream())
                .sorted(Comparator.comparing(Film::getLength))
                .map(Film::getTitle)
                .filter(t -> t.startsWith("A"))
                .limit(10)
                .collect(Collectors.toList());

       List<String> actualFilms = jpaStreamer.stream(of(Language.class).joining(Language$.films))
                .sorted(Language$.name)
                .flatMap(l -> l.getFilms().stream())
                .sorted(Film$.length)
                .map(Film$.title)
                .filter(t -> t.startsWith("A"))
                .limit(10)
                .collect(Collectors.toList());

Actual behavior The list expectedFilms contains 10 films, and the list actualFilms contains 100 films. The generated query reveals that the .limit(10) is applied to the query that fetches languages instead of the flat-mapped Stream of films.

Hibernate: 
    /* <criteria> */ select
        l1_0.language_id,
        f1_0.language_id,
        f1_0.film_id,
        f1_0.description,
        f1_0.last_update,
        f1_0.length,
        f1_0.rating,
        f1_0.rental_duration,
        f1_0.rental_rate,
        f1_0.replacement_cost,
        f1_0.special_features,
        f1_0.title,
        l1_0.name 
    from
        language l1_0 
    left join
        film f1_0 
            on l1_0.language_id=f1_0.language_id 
    order by
        l1_0.name asc limit ?

How To Reproduce Run the two Streams above.

Build tool e.g. Maven 3.9.0

JPAStreamer version e.g. JPAStreamer 3.0.2

JPA Provider e.g. Hibernate 6.0.2.Final

Java Version e.g. Java 17.0.19

julgus commented 1 year ago

Closing as this is related to #354.