JPA CriteriaBuilder - How to use “IN” comparison operator

前端 未结 2 1746
孤城傲影
孤城傲影 2020-11-27 04:17

Can you please help me how to convert the following codes to using \"in\" operator of criteria builder? I need to filter by using list/array of usernames using \"in\".

相关标签:
2条回答
  • 2020-11-27 04:58

    If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

    I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

    List<String> myList = new ArrayList<String> ();
    for (User u : usersList) {
        myList.add(u.getUsername());
    }
    Expression<String> exp = scheduleRequest.get("createdBy");
    Predicate predicate = exp.in(myList);
    criteria.where(predicate);
    

    In order to write more type-safe code you could also use Metamodel by replacing this line:

    Expression<String> exp = scheduleRequest.get("createdBy");
    

    with this:

    Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
    

    If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.

    0 讨论(0)
  • 2020-11-27 05:09

    Not a perfect answer though may be code snippets might help.

    public <T> List<T> findListWhereInCondition(Class<T> clazz,
                String conditionColumnName, Serializable... conditionColumnValues) {
            QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
            addWhereInClause(queryBuilder, conditionColumnName,
                    conditionColumnValues);
            queryBuilder.select();
            return queryBuilder.getResultList();
    
        }
    
    
    private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
                String conditionColumnName, Serializable... conditionColumnValues) {
    
            Path<Object> path = queryBuilder.root.get(conditionColumnName);
            In<Object> in = queryBuilder.criteriaBuilder.in(path);
            for (Serializable conditionColumnValue : conditionColumnValues) {
                in.value(conditionColumnValue);
            }
            queryBuilder.criteriaQuery.where(in);
    
        }
    
    0 讨论(0)
提交回复
热议问题