繁体   English   中英

Hibernate Critieria在条件上将两个表连接到第二个表上,并在第一个表上产生结果

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

我在使用休眠条件时遇到问题,我需要使用条件转换此查询。

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

我需要结果作为表A。

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

        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();

请注意

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

此参数很重要:

JoinType.LEFT_OUTER_JOIN

如果您不使用它,并且您的关系是一对多的,那么它将休眠的1:N经典问题

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM