[英]Criteria joining two tables using more than one parameter
I have two tables which are related: 我有两个相关的表:
+-----------+ +----------+
| First | * 1 | Second |
+-----------+ --------- +----------+
| fk_Second | | id |
| version | | ... |
| ... | | y |
| x | +----------+
+-----------+
Hibernate has a ManyToOne
definition from First
to Second
. Hibernate从First
到Second
具有ManyToOne
定义。 The {fk_Second, version}
is a composite-id
of the First
table (although I don't think it's relevant in this case). {fk_Second, version}
是First
表的composite-id
(尽管在这种情况下,我认为它并不重要)。
I am trying to write Criteria call, which in SQL would look like as: 我正在尝试编写Criteria调用,在SQL中看起来像这样:
SELECT * FROM First WHERE
First.fk_Second = Second.id AND
First.x = Second.y
I'm finding trouble in generating the last bit - the extra join condition. 我在生成最后一位时遇到了麻烦-额外的加入条件。
Criteria c = session.createCriteria(First.class);
.createCriteria("second", "join_between_first_and_second")
.add(Restrictions.eqProperty("y", "x") // <- fails: "x" is not found
I can not use HQL queries in this situation. 在这种情况下,我无法使用HQL查询。 Is there any way writing this differently? 有什么办法可以这样写吗? Can this be written avoiding subquery/ DetachedCriteria
? 可以这样写来避免subquery / DetachedCriteria
吗?
Criteria c = session.createCriteria(First.class, "first");
c.createAlias("first.second", "theSecond");
c.add(Restrictions.eqProperty("first.x", "theSecond.y");
If you don't prepend an alias to your property, the property is considered part of the root entity of the criteria (First in this case). 如果您不对属性添加别名,则该属性将被视为条件根实体的一部分(在本例中为First)。
尝试使用HQL'With '子句。
SELECT f.* FROM First f left join Second s ON f.fk_Second = s.id with f.x = s.y;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.