简体   繁体   English

休眠-有条件的加入

[英]Hibernate - Join with condition in on-clause

I want to join 2 tables and do a query: 我想加入2个表并执行查询:
tableA with columns id, data 具有列ID,数据的tableA
tableB with columns id, key 具有列ID,键的tableB

Say, I have one row in tablea: 说,我在表中有一行:

id=5, data='xyz'

and two rows in tableb: 和tableb中的两行:

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

now I want to run the following SQL: 现在我想运行以下SQL:

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

which gets me a result with one row: 这使我得到一行结果:

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

How can I do that with hibernateTemplate? 我该如何使用hibernateTemplate?

I tried with the following hibernate mapping file: 我尝试了以下休眠映射文件:

<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>

and this java-code-sniplet: 和这个java代码片段:

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

That code generates a somewhat different SQL: 该代码生成了一些不同的SQL:

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

If you map 'tableB' as a OneToMany or OneToOne association in 'zBean', and use HQL instead of a Criteria query, you can use the 'with' clause: 如果将“ tableB”映射为“ zBean”中的OneToMany或OneToOne关联,并使用HQL而不是Criteria查询,则可以使用“ with”子句:

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

Hibernate will generate the 'on' clause as you expect. Hibernate将按照您的预期生成“ on”子句。

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

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