我从JPA查询开始。我试图找出如何将集合设置为'成员'where子句的参数。 采用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;
}
}
这只是Dog的一个实例作为参数。如果我有一个狗和wnat列表来创建一个名为'isAnyOfTheseDogsBelongingToAperson'之类的方法,该怎么办?我是否需要为Dog列表的每个元素多次调用上面的方法,或者有没有办法将集合传递给查询?例如:
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;
}
}
答案 0 :(得分:-2)
如果你只是为'isAnyOfTheseDogsBelongingToAperson'方法增加一个循环怎么办?尝试这样的事情:
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;
}
}
}
否则,您可以尝试与列表的.contains方法进行一些比较。为此,请参阅以下代码:
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;
}
希望这可以帮到你,祝你好运!