I am trying to create a Hibernate specification with parentheses but was not able to do it.
I have many specifications. My problem is with the following specification:
public static Specification<ListingEntity> locations(List<String> locations) {
if (locations == null || locations.isEmpty()) {
return null;
} else {
return (root, query, builder) -> {
Join<ListingEntity, GeoLevelTwoEntity> joinGeoLevelTwo = root.join("geoLevelTwoEntity");
Join<GeoLevelTwoEntity, GeoLevelOneEntity> joinGeoLevelOne = joinGeoLevelTwo.join("geoLevelOneEntity");
Predicate predicate = builder.conjunction();
for (String location : locations) {
if (location.contains("_")) {
String[] locationParts = location.split("_");
Predicate predicateLevelOne = builder.equal(joinGeoLevelOne.get("geographyLevelOne"), locationParts[1]);
Predicate predicateLevelTwo = joinGeoLevelTwo.get("geographyLevelTwo").in(locationParts[0]);
Predicate locationPredicate = builder.and(predicateLevelOne, predicateLevelTwo);
predicate = builder.or(predicate, locationPredicate);
}
}
return predicate;
};
}
}
It creates the following SQL script:
from
listings le1_0
join geo_level_two glte1_0 on glte1_0.id = le1_0.geography_level_two_id
join geo_level_one gloe1_0 on gloe1_0.id = glte1_0.geography_level_one_id
where
1 = 1
or gloe1_0.geography_level_one = ?
and glte1_0.geography_level_two in (?)
or gloe1_0.geography_level_one = ?
and glte1_0.geography_level_two in (?)
order by
(
select
0
) offset ? rows fetch first ? rows only
I want it to create the following way:
where
1 = 1
and ( gloe1_0.geography_level_one = ?
and glte1_0.geography_level_two in (?)
or gloe1_0.geography_level_one = ?
and glte1_0.geography_level_two in (?) )
order by
I have other specifications that create and conditions like and floor = 2 etc. Thus I cannot think it without using parentheses. I think it needs to look like the following:
(geographyL1 = 'New York' and geographyL2 = 'USA' or geographyL1 = 'London' and geographyL2 = 'UK') and floor = 2 and price > 100000
I have no issue with other specifications that generate the following SQL. Each condition has its own separate specification:
floor = 2 and price > 100000 and numberOfRooms = 2
What should I do so that my specification for location lies inside parentheses?