Search code examples
javajpajpql

How to do a JPQL that would filter a collection that does not satisfy a query?


I have a collection idsToCheck I want to do something like

select a.entry from idsToCheck as a where a.entry not in (select d.id from data d)

What I did was for now was

@Query("select count(a) > 0 from Data a where a.id = :id")
boolean isIdExists(String id);


idsToCheck 
  .stream()
  .filter(check-> !artifacts.isIdExists(check))
  .forEach(responseBuilder::addDeletedIds);


Solution

  • It might be possible with JPQL only but since JPQL does not support SET operations and selects are performed against entities (so not against scalars or arrays given as parameters) it might be a complex task to implement.

    I realize that my suggestion is not pure JPQL but it is an alternative to yours to have query more abstract. I assume Spring repository interface in my suggestion but guess it is - with minor modifications - applicable elsewhere also.

    // First fetch all entities in given collection of ids
    @Query("SELECT d.id FROM Data d WHERE id in :idsToCheck")
    Set<String> findByIds(@Param("idsToCheck") Collection<String> idsToCheck);
    
    // find out which ids were not found at all (the needed SET operation)
    default Set<String> findNonExistentIds(Set<String> idsToCheck) {
        idsToCheck.removeAll(findByIds(idsToCheck));
        return idsToCheck;
    }
    

    With native query this should be possible without helper methods.