【问题标题】:Hibernate - Join with condition in on-clauseHibernate - 在子句中加入条件
【发布时间】:2017-10-29 15:13:09
【问题描述】:

我想加入 2 个表并进行查询:
具有列 id、数据的 tableA
具有列 id、键的 tableB

说,我在tablea中有一行:

id=5, data='xyz'

tableb 中有两行:

id=5, key='key1'
id=5, key='key2'

现在我想运行以下 SQL:

select * from tablea a left outer join tableb b on (a.id = b.id and b.key='key3')

这让我得到一个结果:

id=5, data='xyz', key=null

如何使用 hibernateTemplate 做到这一点?

我尝试使用以下休眠映射文件:

<hibernate-mapping package="de.xxx.vo">
<class name="zBean" table="TABLEA">
    <subselect>
        SELECT
            a.id, a.data
        FROM
            tablea a
            LEFT OUTER JOIN tableb b on a.id = b.id
    </subselect>

    <id name="id" column="ID" type="long"/>
    <property name="data" column="DATA" type="string" />
    <property name="key" column="KEY" type="string" />
</class>
</hibernate-mapping>

还有这个 java-code-sniplet:

DetachedCriteria crit = DetachedCriteria.forClass(zBean.class)
    .add(Restrictions.eq("key", "key3"));
List<ListViewDataBean> result = hibernateTemplate.findByCriteria(crit);

该代码生成的 SQL 略有不同:

select * from tablea a left outer join tableb b on (a.id = b.id) where b.key='key3'

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    如果您将“tableB”映射为“zBean”中的 OneToMany 或 OneToOne 关联,并使用 HQL 而不是 Criteria 查询,则可以使用“with”子句:

    select z from zBean z left join z.tableB b with b.key = 'key3'
    

    Hibernate 将按照您的预期生成“on”子句。

    【讨论】:

      猜你喜欢
      • 2015-09-20
      • 2011-09-14
      • 2013-12-23
      • 2012-09-15
      • 2016-12-16
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多