【发布时间】:2013-07-05 08:05:20
【问题描述】:
我的代码是:
Criteria criteriaA = getHibernateSession().createCriteria(entityA.class, "aaa");
Criteria criteriaB = criteriaA.createCriteria("entityB").setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); // It seems that the result transformer don't affect the code...
criteriaA.add( -- some restriction --)
if (orderById) {
criteriaB.addOrder(Order.desc("id"));
}
if (!orderById && orderByDate) {
criteriaB.addOrder(Order.desc("date"));
}
criteriaA.setProjection(Projections.distinct(Projections.property("entityB")));
entityA 和 entityB 具有 oneToMany 关系(一个 entityB 可能有 0..* entityA),但我只能从 B 导航到 A(项目限制.. 无法更改)。
现在,问题是我不需要在返回的结果中重复,我需要对我的结果进行排序。
奇怪的事实是 ORA-01791(告诉我有一个不正确的 orderby)我仅在按日期排序时启动,按 id 排序并没有给我任何问题,但两者都是我想要区分的实体的属性!
为什么我可以按 id 排序但不能按日期排序??
还有其他方法可以做我想做的事情吗?
---- 编辑 -----
正如maby建议的那样,我查看了生成的查询:
DEBUG [org.hibernate.SQL]
select distinct this_.BBB_ID as y0_
from TB_ENTITY_A this_
inner join TB_ENTITY_B entityB_ on this_.BBB_ID=entityB_.BBB_ID
where this_.ANOTHER_ID=? and lower(this_.AAA_VALUE) like ? and this_.AAA_ID in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
order by entityB_.BBB_DATE asc
所以,我的 distinct where 仅适用于外键的 id..
如何强制 Hibernate 选择所有字段?
如果我这样做:
criteriaB.list();
而不是
criteriaA.list():
我会丢失来自条件 A 的过滤器吗?
我也在考虑尝试在 Projection 中设置 entityB 中的所有字段,但我不确定 hibernate 是否可以将结果转换为实体。
【问题讨论】:
-
+1 为解决方案,我将建议自己进行子选择。你也可以把它当作自己的答案。
-
好了,我已经完成了:)