I want to join 2 tables and do a query:
tableA with columns id, data
tableB with columns id, key
Say, I have one row in tablea:
id=5, data='xyz'
and two rows in tableb:
id=5, key='key1'
id=5, key='key2'
now I want to run the following 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?
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:
DetachedCriteria crit = DetachedCriteria.forClass(zBean.class)
.add(Restrictions.eq("key", "key3"));
List<ListViewDataBean> result = hibernateTemplate.findByCriteria(crit);
That code generates a somewhat different 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:
select z from zBean z left join z.tableB b with b.key = 'key3'
Hibernate will generate the 'on' clause as you expect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.