使用JPQL中的IN运算符的枚举列表

时间:2013-06-21 08:54:22

标签: java jpa-2.0 jpql

缺少以下JPQL query

SELECT h FROM WorkFlowHistory h WHERE h.referenceNo = :referenceNo 
AND h.workflowTask IN ('CONFIRMATION','PAYMENT','ISSUING')

错误:

invalid IN expression argument [CONFIRMATION]

动态查询方法

public List<WorkFlowHistory> findWorkFlowHistoryByRefNo(String refNo, WorkflowTask ...workflowTasks) {
    ...
    StringBuffer buffer = new StringBuffer("SELECT h FROM WorkFlowHistory h WHERE h.referenceNo = :referenceNo");
    if(workflowTasks != null && workflowTasks.length > 0) {
        buffer.append(" AND h.workflowTask IN (");
        for (int i = 0; i < workflowTasks.length; i++) {
            buffer.append("'" + workflowTasks[i] + "'");
            if ((i + 1) != workflowTasks.length) {
                buffer.append(",");
            }
        }
        buffer.append(")");
    }
    Query q = em.createQuery(buffer.toString());
    ....
}

我的枚举课

public enum WorkflowTask {
    UNDERWRITING("Underwriting"),
    SURVEY("Survey"),
    APPROVAL("Approval"),
    INFORM("Inform"),
    CONFIRMATION("Confirmation"),
    PAYMENT("Payment"),
    PROPOSAL_REJECT("Proposal Reject"),
    ISSUING("Issuing");

    private String label;

    private WorkflowTask(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}   

1 个答案:

答案 0 :(得分:2)

我认为问题在于您在DB中表示您的Enums。您的枚举如何在数据库OrdinalString中映射?

最好的方法是将您的枚举作为参数占位符放在JPQL查询中:

SELECT h FROM WorkFlowHistory h WHERE h.referenceNo = :referenceNo 
AND h.workflowTask IN :workflowTasks

并将其作为参数添加到您的查询中,如下所示:

...
List<WorkflowTask> workflowTasks=Arrays.asList({WorkflowTask.CONFIRMATION, WorkflowTask.PAYMENT WorkflowTask.ISSUING });
...
Query q = em.createQuery(buffer.toString());
q.addParameter("workflowTasks", workflowTasks);

这样您就不必考虑您的枚举在DB中的表现方式。