Home > Software engineering >  Spring data JPA Specification - return list and limit result-attribute to occur only once in the lis
Spring data JPA Specification - return list and limit result-attribute to occur only once in the lis

Time:10-16

I am trying to build a specification which takes as an input Set UUID fooIds and long olderThanInMillis.

My method should return a List of Result. The Result has a fooId as a field (not id). In the table, there may be many objects with identical fooId. However I wish to get only 1 Result per fooId.

My current specification looks like this:

private Specification<Result> buildSpec(Set<UUID> fooIds, long olderThanMilis)
   {
       Specification<Result> idSpec = (root, query, builder) -> builder.or(builder.in(root.get("fooId")).value(clientPoses));
       Specification<Result> olderThanSpec = (root, query, builder) -> builder.lessThanOrEqualTo(root.get("created"), olderThanMilis);

       return idSpec.and(olderThanSpec);
   } 

I am trying to pack something on top of what I have, but nothing seems to work. Possible workaround is of course not to load from DB a List, but rather load it one by one per fooId and olderThanMillis with limit 1... In case of loading it one by one, is that a bad practice or not? Any advice, please? Thank you...

CodePudding user response:

Usually, this is handled by sorting by something unique and using setMaxResults(1), but I don't know how Spring Data supports this.

  • Related