I am trying to build a SQL where clause using criteriaBuilder and predicates to create some SQL like:
WHERE
(country5_.ctry_iso_cd = 'ESP'
AND datadomain6_.data_dmn_cd = 'MTH'
OR country5_.ctry_iso_cd = 'ESP'
AND datadomain6_.data_dmn_cd = 'SOU'
)
AND NOT ( EXISTS (
SELECT
'NOT READY'
FROM
dc_dca_installation_status collection5_
WHERE
collection0_.installation_id = collection5_.installation_id
) )
the brackets around the list of AND OR pairs are important to separate them from the not exists. This is because of the AND having precedence what i get is
WHERE
country5_.ctry_iso_cd = 'ESP'
AND datadomain6_.data_dmn_cd = 'MTH'
or country5_.ctry_iso_cd = 'ESP'
AND datadomain6_.data_dmn_cd = 'SOU'
AND NOT ( EXISTS (
SELECT
'NOT READY'
FROM
dc_dca_installation_status collection5_
WHERE
collection0_.installation_id = collection5_.installation_id
) )
I can build up all the predicates no problem but I just don't know how to get it to add the brackets in around the AND OR pairs list
the list of AND OR pairs are build like this into 1 list of predicates
countryDomainPredicates.add(cb.and(
cb.equal(countryJoin.get(Country_.ctryIsoCd), ud.getCountryCode()),
cb.equal(dataDomainJoin.get(DataDomain_.code), ud.getDataDomainCode())
and the subquery is added like this
cb.not(cb.exists(subquery));
and the where
critQuery.where(cb.and(array));
Brackets around each AND OR pair would be just as good
I fixed it myself, instead of building up 1 array and converting that into 1 predicate.
i converted the array of AND OR pairs into 1 predicate, added the not exists into another predicate and then used this array of 2 predicates into the where.
List<Predicate> predicates = new ArrayList<>();
predicates.add( addAndOrPairs(cb, root, userDataDomains));
Subquery<String> subquery = createSubQuery(cb, root);
predicates.add(cb.and(cb.exists(subquery).not()));
critQuery.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));