spring-data-jpa icon indicating copy to clipboard operation
spring-data-jpa copied to clipboard

KeysetScrollSpecification null properties support

Open ivan-zaitsev opened this issue 5 months ago • 6 comments

It is documented here that keyset-filtering requires all the keyset properties to be non-nullable.

But will it actually affect indexing/ordering by adding cb.isNull() condition for some of the properties to https://github.com/spring-projects/spring-data-jpa/blob/main/spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/KeysetScrollSpecification.java#L120 ?

Generated query examples:

Map<String, Object> keys = new LinkedHashMap<>();
keys.put("createdAt", entity.getCreatedAt());
keys.put("id", entity.getId());

// Maybe somehow here allow to specify which keys can be null, but at least one key is requred to be not null
KeysetScrollPosition scrollPosition = ScrollPosition.of(keys, ScrollPosition.Direction.FORWARD);

Sort sort = Sort.by(Sort.Direction.ASC, "createdAt", "id")

Function<FluentQuery.FetchableFluentQuery<Entity>, Window<Entity>> queryFunction = query -> query
        .limit(10)
        .sortBy(sort)
        .scroll(scrollPosition);

Specification<Entity> specification = ...;

Window<Entity> result = repository.findBy(specification, queryFunction);
SELECT *
FROM table
WHERE (created_at IS NOT NULL AND created_at > ?) OR
      (created_at IS NULL AND id > ?)  -- use a fallback key like `id` for rows with NULL `created_at`
ORDER BY created_at ASC, id ASC
LIMIT 10;

ivan-zaitsev avatar Sep 08 '24 18:09 ivan-zaitsev