JPA规范ADD Where IN子句

时间:2020-07-01 06:07:03

标签: java spring-data-jpa

我想问一下如何对具有List属性的类使用JPA规范。假设,我们有一个可以同时具有多个角色的用户。我想从给出角色列表和用户ID列表的数据库中获取所有用户

@Entity(name = "UserEntity")
public class User {
    Private Long id;
    private String name;
    private String surname;

   @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "OA_USER_ROLE_DTL", joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID"))
    @OrderBy
    @JsonIgnore
    private Collection<Role> roles;
}

1 个答案:

答案 0 :(得分:1)

回答我的问题

    public class UserSpecification implements Specification<UserEntity> {
    private Set<String> roleNames;
    private Set<Long> userId;
    private Date startDate;
    private Date endDate;
    private String emailId;
    private String userName;
    private String mobileNo;
    private Long clientId;
    @Override
        public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
            List<Predicate> finalPredicate = new ArrayList<Predicate>();
            if (roleNames != null && !roleNames.isEmpty()) {
                Join<UserEntity, Role> userRoleJoin = root.join(ROLES);
                Predicate roleName = userRoleJoin.get(ROLE_NAME).in(roleNames);
                finalPredicate.add(roleName);
            }
            if (userId != null && !userId.isEmpty()) {
                Predicate userIdPredicate = root.get(ID).in(userId);
                finalPredicate.add(userIdPredicate);
            }
            if (!StringUtils.isEmpty(emailId)) {
                finalPredicate.add(criteriaBuilder.equal(root.get(EMAIL_ID), emailId));
            }
            if (!StringUtils.isEmpty(userName)) {
                finalPredicate.add(criteriaBuilder.equal(root.get(USERNAME), userName));
            }
            if (!StringUtils.isEmpty(mobileNo)) {
                finalPredicate.add(criteriaBuilder.equal(root.get(MOBILE_NUM), mobileNo));
            }
            if(clientId!=null && clientId!=0L) {
                finalPredicate.add(criteriaBuilder.equal(root.get(CLIENT_ID), clientId));
            }
            if (startDate != null && endDate != null) {
                Path<Date> path = root.get(CREATED_DATE);
                finalPredicate.add(criteriaBuilder.between(path, startDate, endDate));
            }
            query.distinct(true);
            Predicate and = criteriaBuilder.and(finalPredicate.toArray(new Predicate[finalPredicate.size()]));
            return and;
        }
    }