hibernate使用distinct的条件加入将无效

时间:2011-04-23 09:17:37

标签: java hibernate

当我运行时,我得到了结果查询,我希望实际查询

实际查询(待生成,欲望查询) 不同[ID]

select distinct rc.* from ratecodeparam rcp , ratecodes rc where rc.travelfrom <= '2011-04-22' and rc.travelto >= '2011-04-25' and rc.id = rcp.p_id;

OR

select distinct rc.* from ratecodeparam rcp join ratecodes rc on rc.travelfrom <= '2011-04-22' and rc.travelto >= '2011-04-25' and rc.id = rcp.p_id;

我想要

  

distinct rc。*

代码

我通过了代码,但disticnt rc。*

  session.createCriteria(RateCode.class)
            .add(Restrictions.le("travelFrom", from.getTime()))
            .createCriteria("rateCodeParams", "rcp")
    list = crit.list();

RateCode.hbm.xml

<class catalog="hermes" name="com.RateCode"  table="ratecodes">
        <id name="rateCodeId" type="java.lang.Integer">
            <column name="id"/>
            <generator class="native"/>
        </id>
        <property name="code" type="string">
            <column length="32" name="code" unique="true"/>
        </property>
        <set name="rateCodeParams" cascade="all, delete-orphan" order-by="param">
            <key>
                <column name="p_id"  />
            </key>
            <one-to-many class="com.RateCodeParam" />
         </set>
</class>

RateCodeParam.hbm.xml

<class catalog="hermes" name="com.RateCodeParam" table="ratecodeparam">
        <id name="id" type="java.lang.Integer">
            <column name="id"/>
            <generator class="identity"/>
        </id>       
        <many-to-one  class="com.RateCode" name="rateCode" insert="false" fetch="join" update="false" > 
            <column name="p_id" />
        </many-to-one>
</class>

1 个答案:

答案 0 :(得分:1)

您的查询缺少连接,因为您没有向查询添加一个连接。设置获取模式( setFetchMode )只会向现有连接添加更多详细信息。但在您的查询中它不存在。

正确的查询可能如下所示:

Criteria crit = session.createCriteria(RateCode.class)
    .add(Restrictions.le("travelFrom", from.getTime()))
    .createCriteria("rateCodeParams", "rcp");
list = crit.list();