0

I starting with JPA queries. I'm trying to find out how to set a collection as a parameter of 'member of' where clause. Taking the Model described in Ultimate JPA Queries and Tips List – Part 1

private static boolean isThisDogBelongingToAperson(EntityManager em, Dog dog, String name) {
  Query query = em.createQuery('select count(p) from Person p where :dog member of p.dogs and p.name = :name');
  query.setParameter('dog', dog);
  query.setParameter('name', name);
  try {
   return query.getSingleResult() != null;
  } catch (Exception e) {
   return false;
  }
}

This is taking only one instance of Dog as parameter. What if I have a list of dogs and wnat to create a method named as something like 'isAnyOfTheseDogsBelongingToAperson'. Do I need to call the method above several times for each element for the Dog list, or is there a way to pass the collection to the query? For example:

private static boolean isAnyOfTheseDogsBelongingToAperson(EntityManager em, List<Dog> dogs, String name) {
  Query query = em.createQuery('select count(p) from Person p where :dogs member of p.dogs and p.name = :name');
  query.setParameter('dogs', dogs);
  query.setParameter('name', name);
  try {
   return query.getSingleResult() != null;
  } catch (Exception e) {
   return false;
  }
}
L. Holanda
  • 4,432
  • 1
  • 36
  • 44
  • you can pass collections to `setParameter`, also` getSingleResult` throws an exception if there is no result - it does not return null - http://stackoverflow.com/questions/2002993/jpa-getsingleresult-or-null, also this question is similar to yours http://stackoverflow.com/questions/21644726/jpa-find-all-articles-that-have-a-common-set-of-tags – Svetlin Zarev Mar 08 '14 at 11:39

1 Answers1

-2

What if you just increment an loop for your 'isAnyOfTheseDogsBelongingToAperson' method? Try something like this:

private static boolean isAnyOfTheseDogsBelongingToAperson(EntityManager em, List<Dog> dogs, String name) {
  for (Dog dog : dogs){
      Query query = em.createQuery('select count(p) from Person p where :dog member of p.dog and p.name = :name');
      query.setParameter('dog', dog);
      query.setParameter('name', name);
      try {
       return query.getSingleResult() != null;
      } catch (Exception e) {
       return false;
      }
  }
}

Otherwise you can try some comparison with .contains method of the the list. To do it see the code below:

private static boolean isAnyOfTheseDogsBelongingToAperson(EntityManager em, List<Dog> dogs){
    boolean result = false;
    List<Dog> dogsWithOwners = new ArrayList<Dog>();
    Query query = em.createQuery('select p.dog from Person');
    dogsWthOwners = query.getResultList();
    for (Dog dog : dogs){
        if (dogsWithOwners.contains(dog){
            result = true;
        }
    }
    return result;
}

Hope this can help you, good luck!

N0nbot
  • 190
  • 1