使用 jpa 条件创建动态查询

Creating dynamic query using jpa criteria

我使用 jpa 条件创建了动态查询,但是当我执行 userGroupSubquery.select(userGroupsRoot);

时,一对额外的括号被添加到要 select 的列中

生成的查询

select (securitygr3_.group_name, securitygr3_.user_name) 来自 gm.security_groupings securitygr3_ 其中 1=1 and securitygr3_.user_name='xxx' and (securitygr3_.group_name 在 ('XYZ'))

预期查询:

select securitygr3_.group_name, securitygr3_.user_name 来自 gm.security_groupings securitygr3_ 其中 1=1 and securitygr3_.user_name='xxx' and (securitygr3_.group_name 在 ('XYZ'))

Subquery<SecurityGroupings> userGroupSubquery = secUsersQuery.subquery(SecurityGroupings.class);
            Root<SecurityGroupings> userGroupsRoot = userGroupSubquery.from(SecurityGroupings.class);
            Path<SecurityGroupingsId> secGroupId = userGroupsRoot.get("id");
            Path<SecurityUsers> secUsers = secGroupId.get("securityUsers_1");
            Path<SecurityUsers> securityUsers = secGroupId.get("securityUsers");
            Path<String> su_name = secUsers.get("name");
            Path<String> name = securityUsers.get("name");
            userGroupSubquery.select(userGroupsRoot);
            userGroupSubquery.getCompoundSelectionItems();



//userGroupSubquery.where(criteriaBuilder.equal(pet.get(SecurityGroupingsId_.id), root.<String>get("name")));
            Predicate restrictions3 = criteriaBuilder.conjunction();
            restrictions3 = criteriaBuilder.and(restrictions3, criteriaBuilder.and(criteriaBuilder.equal(su_name, dto.getUserId().trim().toUpperCase())));
            restrictions3 = criteriaBuilder.and(restrictions3, criteriaBuilder.and(name.in(userGroups)));
            userGroupSubquery.where(restrictions3);
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(userGroupSubquery));
        }
        secUsersQuery.where(restrictions);

只是我在select (securitygr3_.group_name, securitygr3_.user_name)处多了一对括号 这给了我 ora-00907 缺少右括号错误。我确定它来自 userGroupSubquery.select(userGroupsRoot) 但我不确定为什么。请帮忙

我得到了上述的解决方案。当实体有复合键时,则在 JPA 标准中而不是做

userGroupSubquery.select(userGroupsRoot);

我们应该做的

userGroupSubquery.select(userGroupsRoot.get("id"));

其中 id 是复合 id。