I have a Unit which has a UnitType and an Organization. I have a Contract which has a collection of UnitTypes and an Organization. I would like to select the unit, and either the contract that has the Unit's UnitType in its collection, OR the UnitType that has an empty UnitType collection if there is no match.
To clarify, in every case I want to select the Unit. If there exists a Contract which has the unit's specified type in the contract's collection of UnitTypes then I would like to select that contract. If such a contract doesn't exist, then I would like to select the Contract that has no UnitTypes at all. In other words, I would like the contract that applies to this unit's type, but if it doesn't exist I'll take the contract that is unit type agnostic as the default.
Example 1:
Unit A has type XYZ.
Contract B has types [ ABC, DEF ]
Contract C has types []
in this case I would select the unit and Contract C because B has no match on type.
Example 2:
Unit A has type XYZ
Contract B has types [XYZ, ABC]
Contract C has types []
In this case I would select Contract B because it matches the type of the Unit.
The following query works for Example 2, but not for Example 1.
SELECT NEW mypackage.view.MyAggregateView(
u
, MAX(sc.serviceDate)
, c.survey.key )
FROM Contract c
, Unit u
LEFT JOIN u.serviceCalls sc
WHERE c.organization.key = u.organization.key
AND u.organization.key = :organizationKey
AND ((u.unitType MEMBER OF c.unitTypes)
OR (c.unitTypes IS EMPTY))
GROUP BY u, c.survey.key
How do I make this work in both cases and ensure I get the correct Contract?
Yet Another Example:
I've recently run into this again. I have a region, which has a collection of zip codes and optionally a collection of organizations. I also have a Unit, which has a 1-1 to an organization and has a single zip code. I want to get all the appropriate units within the region's zip codes. If the region has no organizations then I should get all units within the zip codes, otherwise I should only get the units that have an organization that matches one of the organizations specified within the region.
Here's my query
Select u.key, u.organization.key
from Unit u, Region r
where r.key = -1
and u.address.postalCode member of r.zips
and r.organizations is empty
This query gets me all of my expected results. The following query, which should in no way restrict the result set since it's only adding an OR, gives me no results.
Select u.key, u.organization.key
from Unit u, Region r
where r.key = -1
and u.address.postalCode member of r.zips
and ((r.organizations is empty) OR (r.organizations is not empty and u.organization member of r.organizations))
I'm using eclipse link 2.0.1 against postgres 9. I also got the same result with eclipselink 2.2.0.