如何为以下查询创建jpa规范或条件查询的谓词

时间:2019-08-20 07:35:19

标签: java spring-boot jpa spring-data-jpa criteria

我正在尝试为两个日期为date1和date2之间的过滤器数据创建JPA规范,我试图通过子查询创建,但到目前为止还算不上好运,请尽可能提供帮助。 我正在尝试为以下SQL查询创建规范,

select
    * from
    subscription sub join (
        select subscription_id,
        max(output_date) as max_output_date
    from
        subscription_package
    where
        package_status = 'COMPLETE'
    group by
        subscription_id) sp on
    sub.id = sp.subscription_id where
    max_output_date between 'date1' and 'date2'

以下是在JPA中创建的查询:

            Subquery<Date> datequery = query
            .subquery(Date.class);
        Root<SubscriptionPackage> dateRoot = datequery
            .from(SubscriptionPackage.class);

        Subquery<SubscriptionPackage> subquery = query
            .subquery(SubscriptionPackage.class);
        Root<SubscriptionPackage> subqueryRoot = subquery
            .from(SubscriptionPackage.class);

        datequery.select(criteriaBuilder
            .greatest(subqueryRoot.<Date>get("outputDate")));
        datequery.where(criteriaBuilder.equal(subqueryRoot.get("PackageStatus"),
                'COMPLETE'));
        datequery.groupBy(subqueryRoot.get("subscription"));

无法将日期查询的结果用于

之类的比较
query.where(criteriaBuilder.between(datequery., outFrom, outTo));

1 个答案:

答案 0 :(得分:0)

我不知道您为什么要使用子查询,并且可以将简单的Spring数据jpa与联接一起使用来获得所需的结果。 Please check these examples

用于日期比较:

criteriaBuilder.between(root.get("createdDate"), fromDate, toDate));