Union-select aliases not injected before "clazz_" conditions in HQL query

Description

When generating a query on a joined-subclass or table-per-class hierarchy (involving a select-union on the concrete tables), Hibernate does not inject the alias before the "clazz_" condition in the WHERE block.

Consider the class ClassOfInterest with members:

long Id;
OtherClassIface otherEntity;

There is also the superclass type OtherClassIface and the subclasses OtherClassA and OtherClassB. If we run the following query:

from ClassOfInterest c
left join c.otherEntity myAlias1
left join c.otherEntity myAlias2
where myAlias1.class = OtherClassA
and myAlias2.class = OtherClassB
and (myAlias1.fieldA = '123' or myAlias2.fieldB = '456')

The following SQL is generated:

select
classofint0_.id as id1_0_0_,
otherclass1_.id as id1_3_1_,
otherclass2_.id as id1_3_2_,
classofint0_.otherEntity_id as otherEnt2_0_0_,
otherclass1_.fieldA as fieldA1_1_1_,
otherclass1_.fieldB as fieldB1_2_1_,
otherclass1_.clazz_ as clazz_1_,
otherclass2_.fieldA as fieldA1_1_2_,
otherclass2_.fieldB as fieldB1_2_2_,
otherclass2_.clazz_ as clazz_2_
from
ClassOfInterest classofint0_
left outer join
(
select
id,
fieldA,
null as fieldB,
1 as clazz_
from
OtherClassA
union
all select
id,
null as fieldA,
fieldB,
2 as clazz_
from
OtherClassB
) otherclass1_
on classofint0_.otherEntity_id=otherclass1_.id
left outer join
(
select
id,
fieldA,
null as fieldB,
1 as clazz_
from
OtherClassA
union
all select
id,
null as fieldA,
fieldB,
2 as clazz_
from
OtherClassB
) otherclass2_
on classofint0_.otherEntity_id=otherclass2_.id
where
clazz_=1
and clazz_=2
and (
otherclass1_.fieldA='123'
or otherclass2_.fieldB='456'
)

This generates a JDBC exception due to the ambiguous column name. Instead, the marked block should be preceded by the alias of the union select:

otherclass1_.clazz_ = 1
and otherclass2_.clazz_ = 2

(i.e. add the parts in bold)

Problem originally noted in Oracle JDBC but also reproduces in SQLite, which is used in attached test-case.

Environment

None

Status

Assignee

Vlad Mihalcea

Reporter

Peter Holvenstot

Fix versions

Labels

None

backPortable

Backport?

Suitable for new contributors

Yes, likely

Requires Release Note

None

backportDecision

None

Components

Affects versions

Priority

Major
Configure