【问题标题】:Hibernate Critieria join two tables with condition on 2nd table and result the 1st tableHibernate Criteria 将两个表与第二个表的条件连接起来,结果是第一个表
【发布时间】:2011-04-06 22:21:48
【问题描述】:

我有一个使用 Hibernate Criteria 的问题,我需要使用条件转换此查询。

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

我需要表格 A 的结果。

【问题讨论】:

    标签: java hibernate criteria


    【解决方案1】:

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

            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
    

    如果你没有使用它,并且你的关系是一对多的,它会碰到hibernate的1:N经典问题

    【讨论】:

    • 能否请您也在这里写下生成的 sql 查询?表和列名与相关示例不匹配。
    【解决方案2】:

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

    如果实体定义中未指定关联,则不能使用条件。 可以使用HQL做内连接(需要写implicit join notation),做左连接需要使用原生SQL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 2021-08-23
      相关资源
      最近更新 更多