我下面有以下代码片段。这两个开关块之间的唯一区别是我在调用criteriaBuilder.asccriteriaBuilder.desc的事实。有没有一种方法可以避免使用switch语句或if语句,而可以动态地调用适当的criteriaBuilder“ sortdirection”方法?

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = criteriaBuilder.createTupleQuery();
Root<Cases> caseRoot = criteria.from(Cases.class);

switch (sortDirection) {
    case "asc":
        switch (orderBy) {
            case 0:
                criteria.orderBy(criteriaBuilder.asc(caseRoot.get(Cases_.caseid)));
                break;
            case 1:
                criteria.orderBy(criteriaBuilder.asc(caseRoot.get(Cases_.dtype)));
                break;
            case 2:
                criteria.orderBy(criteriaBuilder.asc(caseRoot.get(Cases_.title)));
                break;
        }
        break;
    case "desc":
        switch (orderBy) {
            case 0:
                criteria.orderBy(criteriaBuilder.desc(caseRoot.get(Cases_.caseid)));
                break;
            case 1:
                criteria.orderBy(criteriaBuilder.desc(caseRoot.get(Cases_.dtype)));
                break;
            case 2:
                criteria.orderBy(criteriaBuilder.desc(caseRoot.get(Cases_.title)));
                break;
        }
        break;
}


例如。下面是完全组成的代码,但希望它对我的意思有所帮助。

sortDirectionMethod = criteriaBuilder.asc; // Somehow store the criteriaBuilder method of either asc or desc.
switch (orderBy) {
    case 0:
        criteria.orderBy(sortDirectionMethod(caseRoot.get(Cases_.caseid)));
        break;
    case 1:
        criteria.orderBy(sortDirectionMethod(caseRoot.get(Cases_.dtype)));
        break;
    case 2:
        criteria.orderBy(sortDirectionMethod(caseRoot.get(Cases_.title)));
        break;
}
break;

最佳答案

像这样尝试enume

public enum OrderBy {
caseid(0), dtype(1), title(2);

private int type;

public OrderBy(int type) {
    this.type = type;
}

}

//then instead of using switch you can use enum like this:

OrderBy orderByEnum = OrderBy.valueOf(orderBy);
criteria.orderBy("asc".equals(sortDirection) ? criteria.orderBy(criteriaBuilder.asc(orderByEnum.name()) :
criteria.orderBy(criteriaBuilder. desc(orderByEnum.name()));

关于java - 不带Switch语句的Dynamic OrderBy CriteriaBuilder,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61809577/

10-10 11:53