JPA子查询中“订购依据”的替代方法

时间:2018-07-11 17:21:33

标签: postgresql jpa criteria-api

我在postgres中有一个查询,如下所示:

SELECT op.* 
FROM opportunity op INNER JOIN quote q ON q.id = 
    (SELECT q.id FROM quote q WHERE q.op_id = op.id 
     ORDER BY q.createddate DESC LIMIT 1)
WHERE ((q.accepted = true) OR (q.rejected = false))
  AND op.op_type IN ('Type 1', 'Type 2')

将其转换为JPA时出现的问题是,子查询不允许使用Order by和Limit,因此我只能这样做。同样不确定如何加入表格:

        public Specification<Opportunity> cleaningOpps(Boolean withStatus, String[] statuses){
    return (root, query, builder) -> {

        List<Predicate> filters = new ArrayList<>();
        if(withStatus != null){
            Subquery<Quote> subquery = query.subquery(Quote.class);
            Root<Quote> quote = subquery.from(Quote.class);
            List<Predicate> subqueryFilters = new ArrayList<>();
            subqueryFilters.add(builder.equal(root.get("id"), quote.get("op_id")));
            //Some more filters for the subquery...
            subquery.select(quote).where(builder.and(subqueryFilters.
                    toArray(new Predicate[subqueryFilters.size()])));//Need group by and limit as well
            filters.add(builder.exists(subquery));
            Join<Quote, Opportunity> joinQuote = root.join("quotes");
            //Probably I'll use the joinQuote for some more filtering

        }
        //Some more filters...
        return builder.and(filters.toArray(new Predicate[filters.size()]));
    };
}

我不知道如何在子查询中插入订单和限制。除了使用本机查询之外,是否可以解决此问题或其他任何想法?

0 个答案:

没有答案