I'm trying to convert the below query into a JPA specification in order to enable more flexible querying of my Rule entities, but i don't find any way of translating the below SQL query into a specification. I've been looking for possibilities of querying for "disctint on" with specs but i can't find any.
SELECT DISTINCT ON (name, key) * FROM (SELECT * FROM rules WHERE activated_at < NOW() AND name IN (?1) AND key IN (?2) ORDER BY activated_at DESC) AS tmp;
The above query gives me 1 rule per combination of name + key, with the most recent activated_at timestamps for each combination.
Some background:
- A specific rule is identified with name + key
- There can be multiple records with the same name + key, where the currently active rule is the one with the maximum activated_at timestamp, but is not a future value.
The IN clauses are straight forward with predicates like the below, but i can't find a way of querying for the most recent activated_at timestamp.
return (root, query, criteriaBuilder) -> root.get(key).in(keys);
Is this possible to achieve with JPA specifications?
Does anyone have any directions or finger pointers on how it can be achieved?