java Hibernate Critieria 将两个表与第 2 个表的条件连接起来并生成第一个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5573693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:43:29  来源:igfitidea点击:

Hibernate Critieria join two tables with condition on 2nd table and result the 1st table

javahibernatecriteria

提问by changeme

I have a question using Hibernate Criteria, I need to convert this query using criteria.

我有一个使用 Hibernate Criteria 的问题,我需要使用标准来转换这个查询。

SELECT * FROM A a_ INNER JOIN B b_ ON a_.column1=b_.column1 AND b_.column2 IN (X,Y) AND active='Y';

SELECT * FROM A a_ INNER JOIN B b_ ON a_.column1=b_.column1 AND b_.column2 IN (X,Y) AND active='Y';

I need the result as table A.

我需要表 A 的结果。

采纳答案by Reddy

If the associations are defined, see http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html#querycriteria-associations

如果定义了关联,请参阅http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html#querycriteria-associations

In case associations are not specified in the entities definition, you can't use criteria. You can use HQL to do inner joins (need to write in implicit join notation), for doing left joins you have to use native SQL.

如果实体定义中未指定关联,则不能使用条件。您可以使用 HQL 进行内连接(需要用隐式连接表示法编写),为了进行左连接,您必须使用本机 SQL。

回答by Dennis Chen

I just solved this issue, here is my code

我刚刚解决了这个问题,这是我的代码

        Criteria criteria = session.createCriteria(ProductOffer.class);
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

        Date effDate = TypeConvertUtil.toDate(param.get("effDate"));

        criteria.add(Restrictions.le("effDate", effDate));
        criteria.add(Restrictions.gt("expDate", effDate));


        criteria.createAlias("productOfferPropDefs", "def",JoinType.LEFT_OUTER_JOIN);
        criteria.setFetchMode("productOfferPropDefs", FetchMode.JOIN);
        criteria.add(Restrictions.le("def.effDate", effDate));
        criteria.add(Restrictions.gt("def.expDate", effDate));


        criteria.createAlias("def.productOfferProps", "prop",JoinType.LEFT_OUTER_JOIN);
        criteria.setFetchMode("def.productOfferProps", FetchMode.JOIN);
        criteria.add(Restrictions.le("prop.effDate", effDate));
        criteria.add(Restrictions.gt("prop.expDate", effDate));

        productOfferList = criteria.list();

Please beware that

请注意

criteria.createAlias("productOfferPropDefs", "def",JoinType.LEFT_OUTER_JOIN);

this parameter is important:

这个参数很重要:

JoinType.LEFT_OUTER_JOIN

if you did not use it, and your relation is one-to-many, it will hit the 1:N classic issue for hibernate

如果您没有使用它,并且您的关系是一对多的,则会遇到休眠的 1:N 经典问题