使用规范的Spring Data jpa“IN”子句

jvlzgdj9  于 2023-02-04  发布在  Spring
关注(0)|答案(1)|浏览(160)

我试图从数据库中获取记录使用 spring data jpa 规范API。在这里我需要把一个条件“在”子句的状态列,为此我的代码如下。

public static Specification<UserEntity> userSpecificationsforOperator(String orgName, String groupID,
            List<String> status, Date startDate, Date endDate) {
        return (root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (orgName != null) {
                Join<UserEntity, OrganizationEntity> organization = root.join("organization");
                predicates.add(builder.equal(organization.get("name"), orgName));
            }
            /*
             * if (groupID != null) {
             * predicates.add(builder.equal(root.get("refApprovalGroupId"), groupID)); }
             */

            if (status != null && status.size()>0) {
                predicates.add(root.get("status").in(status));
            }

            if (startDate != null) {
                predicates.add(builder.greaterThanOrEqualTo(root.get("createdDate"), startDate.toInstant()));
            }
            if (endDate != null) {
                predicates.add(builder.lessThanOrEqualTo(root.get("createdDate"), endDate.toInstant()));
            }
            Predicate[] p = predicates.toArray(new Predicate[predicates.size()]);
            return p.length == 0 ? null : p.length == 1 ? p[0] : builder.and(p);
        };
    }

上面的代码在cosole中生成如下查询

SELECT userentity0_.id                    AS id1_68_,
       userentity0_.created_by            AS created_2_68_,
       userentity0_.created_date          AS created_3_68_,
       userentity0_.last_modified_by      AS last_mod4_68_,
       userentity0_.last_modified_date    AS last_mod5_68_,
       userentity0_.group_id              AS group_id6_68_,
       userentity0_.group_name            AS group_na7_68_,
       userentity0_.is_enrollment_updated AS is_enrol8_68_,
       userentity0_.is_federated          AS is_feder9_68_,
       userentity0_.name                  AS name10_68_,
       userentity0_.organization_id       AS organiz17_68_,
       userentity0_.ref_approval_group_id AS ref_app11_68_,
       userentity0_.reference_name        AS referen12_68_,
       userentity0_.status                AS status13_68_,
       userentity0_.uims_id               AS uims_id14_68_,
       userentity0_.user_status           AS user_st15_68_,
       userentity0_.version               AS version16_68_
FROM   user userentity0_
       INNER JOIN organization organizati1_
               ON userentity0_.organization_id = organizati1_.id
WHERE  organizati1_.name ='utopia'
       AND ( userentity0_.status =(?,?)

当我把查询带入数据库工具并传递值时,我得到了数据。但当从应用程序运行时,我没有得到数据。在这里,我了解到我能够正确生成查询,但我的值没有正确传递。因此,您能否建议我如何让我的代码返回数据。

olmpazwi

olmpazwi1#

也许是它的实施导致了这个问题...
来,用这个,如果管用就告诉我

if (status != null && status.size()>0) {
    predicates.add(builder.in(root.get("status")).value(status));
}

相关问题