spring-projects / spring-data-jpa

Simplifies the development of creating a JPA-based data access layer.
https://spring.io/projects/spring-data-jpa/
Apache License 2.0
2.93k stars 1.39k forks source link

JpaSpecificationExecutor distinct find by with limit #3426

Closed frostedpenguin closed 2 months ago

frostedpenguin commented 2 months ago

I am having this findBy call where I am using distinct through the specification like so

repo.findBy(specification, q -> q.limit(limit).as(GeneralSearchProjection.class).all());

I am adding distinct through the specification

return ((root, query, cb) ->
        {
            query.distinct(true);
            return ...;
        })

the query generated by hibernate looks like this

select
        * 
    from
        (select
            distinct ck1_0.seq c0,
             ck1_0.desc c1
            rownum rn 
        from
            table ck1_0 
       ) r_0_ 
    where
        r_0_.rn<=? 
    order by
        r_0_.rn

the distinct won't work of course because of rownum column! Is this actually possible to be done?

mp911de commented 2 months ago

Care to add the SQL output and what you're expecting?

quaff commented 2 months ago

It's handled by Hibernate, I think you should upgrade your oracle database to at least 12c, then hibernate will use ANSI SQL standard syntax FETCH FIRST m ROWS ONLY and OFFSET n ROWS FETCH NEXT m ROWS ONLY instead of ROWNUM.

mp911de commented 2 months ago

Thanks @quaff. As. @quaff mentioned, SQL is generated by Hibernate and there's nothing Spring Data can do about.

frostedpenguin commented 2 months ago

@quaff yep you are right it is a legacy db issue, there is no valid SQL that could make this work either way! Anyway, thanks for the response!