Hibernate,处理Criteria和左外连接条件

时间:2017-06-07 13:01:11

标签: java hibernate

我现有一段代码如下:

Criteria crit = session.createCriteria(myClass);
crit.createAlias(TAB1, TAB1, JoinType.LEFT_OUTER_JOIN);
crit.createAlias(TAB1 + ".table2", TAB2, JoinType.LEFT_OUTER_JOIN);
crit.add(Restrictions.eq(TAB1 + ".deleted", Boolean.FALSE));
crit.add(Restrictions.eq(TAB2 + ".id", someId));

这会“生成”一个SQL查询,如下所示:

SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id
WHERE tab1_.deleted=0
AND tab2_.id = 1234

我需要将过滤器放在JOIN条件而不是WHERE子句中。

要明确,我需要进行以下查询:

SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id AND tab1_.deleted=0
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id AND AND tab2_.id = 1234

我该怎么做?

谢谢

2 个答案:

答案 0 :(得分:3)

您正在使用:

crit.createAlias(${table}, ${alias}, ${joinType});

你应该可以使用:

crit.createAlias(${table}, ${alias}, ${joinType}, ${Criterion});

虽然我在代码库中找不到一个例子,但我希望这会有效。

答案 1 :(得分:2)

以下是来自Hibernates汇合页面的一个不错的例子:

public class PersonDao extends HibernateDaoSupport {
   public List<Person> findByName() { 
      Criteria criteria = getSession().createCriteria(Person.class, "p");
      criteria.createCriteria("p.names", "names", JoinType.INNER_JOIN, Restrictions.eq("name", "John")); 
      return criteria.list(); 
   }
}

<强>可生产

select this_.id as y0_ from person this_ 
inner join debtor_info this_1_ on this_.id=this_1_.id 
left outer join person_person_name personname3_ on this_.id=personname3_.person_id and ( name1_.name=? ) 
left outer join person_name name1_ on personname3_.person_name_id=name1_.id and ( name1_.name=? )

通过该示例,我相信您的代码应该类似于

Criteria crit = session.createCriteria(MyClass.class, "mine");
crit.createAlias("mine.names", "name", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("name", Boolean.FALSE));
crit.createAlias("q.id", "id", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("id", someId));