Let's say I have the following tables:

TABLE1:
ID number
NAME varchar

TABLE2:
ID number (foreign key from first table)
KEY varchar
VALUE varchar

Table 2 could have records for elements in table 1, but not always.

I need a Named Query that will get all IDs from Table 1 and, if available, the infos for a specific key on table 2 or null values if there's no record in Table2, something like this:

select Table1.Id, Table1.Name, Table2.Value
from Table1
left Join Table1.Table2
where Table1.Id in (?)
and Table2.key = 'someKey'

However, this query will only bring results if Table2 has Data for the records in Table1.

I already have the relationship between Table1 and Table2 set as something like:

<map name="Table2" table="Table2" cascade="all-delete-orphan" inverse="true" lazy="true" batch-size="20">
    <cache usage="nonstrict-read-write"/>
    <key column="ID"/>
    <index column="KEY" type="string"/>
    <one-to-many class="somePersistentClass"/>
</map>

How can I build a query that will do what I need? For DB2 here's a working query for what I need:

select Table1.Id, Table1.name, Table2.Value
from Table1
left Join Table2 on Table1.id = Table2.id and Table2.key = 'someKey'
and Table1.Id in (....)

However, I can't find a way that the named query makes the outer join so I get null values when I have no results in Table2, assuming that I need to filter Table2 by a KEY apart from the ID the join has.

有帮助吗?

解决方案

Well, after a bit of research, found answer to my own question...

select Table1.Id, Table1.Name, Table2.Value
from Table1
left outer Join Table1.Table2 with Table2.key = 'someKey'
where Table1.Id in (?)

Strange thing I didn't find this on the Hibernate documentation, but well, it's now doing what I expected.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top