我在Hibernate(JPA),PostgreSQL和排序方面有一些问题。
例如,我们有两个表(映射到实体):
- Pets (id (id), PetTypes (types_id), description (description))
- PetTypes (id (id), name (name))
不需要type_id字段(限于pet_types表)。
例如,在pets表中有10行(在1、2和3行,type_id为null)。 我需要使用HQL或JPA标准通过pet_types.name订购pets表(但我认为JPA不支持它)。
问题:如果type_id为null,则pets表中的值未按顺序选择。
我可以尝试使用下一个解决方案:
FROM Pets pets ORDER BY pets.petTypes.name ASC NULLS LAST
FROM Pets pets ORDER BY CASE WHEN pets.petTypes IS NULL THEN 0 ELSE 1 END, ORDER BY pets.petTypes.name ASC NULLS LAST
FROM Pets pets ORDER BY CASE WHEN pets.petTypes.name IS NULL THEN 0 ELSE 1 END, ORDER BY pets.petTypes.name ASC NULLS LAST
FROM Pets pets LEFT JOIN pets.petTypes ORDER BY pets.petTypes.name ASC NULLS LAST
FROM Pets pets ORDER BY pets.petTypes ASC NULLS LAST, pets.petTypes.names ASC
FROM Pets pets ORDER BY CASE WHEN pets.petTypes IS NULL OR pets.petTypes.name IS NULL THEN 0 ELSE 1 END, ORDER BY pets.petTypes.name ASC
但是什么都行不通。 选择后,我们有7行而不是10行。 有任何想法吗?
我不能通过HQL使用UNION语句。 自2005年以来,它是开放的Hibernate错误。
编辑
感谢Rodrigo Menezes。 此解决方案有效:
select p from Pets p
left join p.petTypes pt
order by case when pt is null then 0 else 1 end, pt.name
可能是您需要两个订单(不确定)。 因为" pets.petTypes"为空,所以不是pets.petTypes.name还是? 类似于ORDER BY pets.petTypes ASC NULLS LAST,pets.petTypes.names ASC
是的,我尝试使用此方法。 没用。 我更新上面的问题。
排序顺序应该对行数没有影响。 您可以发布原始SQL转储吗?
Hibernate为Pets和PetTypes表生成CROSS JOIN语句
也许您的HQL正在生成内部或交叉联接。
您可以强制左联接:
select p from Pets p
left join p.petTypes pt
order by case when pt is null then 0 else 1 end, pt.name
我做了一个案例测试并工作:
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
PetTypes dog = new PetTypes();
dog.setName("Dog");
dog.setId(1);
PetTypes cat = new PetTypes();
cat.setName("Cat");
cat.setId(2);
session.save(dog);
session.save(cat);
int id = 1;
Pets joe = new Pets();
joe.setId(id++);
joe.setDescription("Joe");
Pets x = new Pets();
x.setId(id++);
x.setDescription("Sarah");
x.setPetTypes(dog);
Pets y = new Pets();
y.setId(id++);
y.setDescription("Jakob");
y.setPetTypes(cat);
Pets z = new Pets();
z.setId(id++);
z.setDescription("Xena");
z.setPetTypes(cat);
session.save(joe);
session.save(x);
session.save(y);
session.save(z);
session.getTransaction().commit();
Query q = session.createQuery("select p from Pets p"
+"left join p.petTypes pt"
+"order by case when pt is null then 0 else 1 end, pt.name");
List resultList = q.list();
System.out.println("num of employess:" + resultList.size());
for (Pets next : resultList) {
System.out.println("pet" + next);
}
}
结果:
num of pets:4
pet Pets [description=Joe, petTypes=null]
pet Pets [description=Jakob, petTypes=PetTypes [name=Cat]]
pet Pets [description=Xena, petTypes=PetTypes [name=Cat]]
pet Pets [description=Sarah, petTypes=PetTypes [name=Dog]]