'JPA Specification subquery with AND doesn't work as expected
I'm having a weird issue, I need to connect a View (Workbench) with a table (FA_TICKET), to stablish this connection I use IN operator with subselect... This is going ok... But... When I try to add a new filter to it, it not resolves.
Subquery<Workbench> subFr = query.subquery(Workbench.class);
Root<FrTicket> rootFrTicket = subFr.from(FrTicket.class);
subFr.select(rootFrTicket.get("ticketId"));
Predicate pred = root.get("ticketNum").in(subFr);
criteriaBuilder.and(pred, criteriaBuilder.equal(root.get("type"), TicketType.FR_TICKET));
predicates.add(pred);
....
//predicates is defined at begining and have other filters
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
When I see the sub-query section, it should be like:
select .... from Workbench where ... and (ticketNum in (SUBSELECT) and type = ?)
But... The line about ticket type is never resolved and I see:
select .... from Workbench where ... and (ticketNum in (SUBSELECT))
If I change the order when define the and, I see this:
Predicate pred = criteriaBuilder.equal(root.get("type"), TicketType.FR_TICKET);
criteriaBuilder.and(pred, root.get("ticketNum").in(subFr));
select .... from Workbench where ... and (type = ?)
How I can include this type in the same group? Because I need to stablish a filter with other kind of Ticket entities, with a different type.
Thanks
Solution 1:[1]
Looks like the problem apears with enums, they are problematic with CriteriaBuilder class.
So, if I make this change:
Subquery<Workbench> subFr = query.subquery(Workbench.class);
Root<FrTicket> rootFrTicket = subFr.from(FrTicket.class);
subFr.select(rootFrTicket.get("ticketId"));
Predicate pred = root.get("ticketNum").in(subFr);
criteriaBuilder.and(pred, criteriaBuilder.equal(root.get("type").as(String.class), TicketType.FR_TICKET).name());
predicates.add(pred);
....
//predicates is defined at begining and have other filters
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
Works smooth.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nacho Escursell |
