假设我有两个实体,第一个
//Annotations skipped
public class Person {
List<Name> names;
//getter,setter
}
public class Name {
String name;
//getter, setter
}
我想使用 JPA(Hibernate) 根据名称进行搜索和排序
我写了一个查询;
SELECT entity FROM person entity LEFT JOIN entity.names as names
WHERE names.name like :keyword ORDER BY names.name
当有一个人的名字时就没有问题。如果存在多个名称,JPA 将为每个名称返回一个 Person。如果我这次使用 Distict
,hibernate 会警告我要区分必须按部分排序。
如何解决这个问题
最佳答案
我建议您将所有人都列入列表,例如 List<Person> persons
然后使用 Collections.sort(persons, customComparator);
对列表进行排序你的Comparator
在哪里实现可能如下所示:
class CustomPersonComparator implements Comparator<Person>{
@Override
public int compare(Person o1, Person o2) {
return 0;//TODO for you: perform your names comparision here and return int comparison result accordingly.
}
}
您可以阅读有关比较器的实现 here
关于java - JPA 中实体列表的搜索和排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58724714/