如何在Hibernate Where子句中使用CASE WHEN

时间:2015-05-27 08:06:44

标签: java mysql hibernate hql

Plase举例说明在HQL中使用CASE WHEN

我在我的代码中使用了以下查询。

int receiptNumber = 100;
String hql = "SELECT b FROM OOPExtract as b "
                +"WHERE "
                +" b.tranStatId =" +receiptNumber+ " AND " 
                +" b.orderType IN ('EMERGENCY', 'PLENARY', 'PETITION','EXTENSION','MOTION') AND "
                +" CASE WHEN b.orderType == 'MOTION' " `enter code here`
                +  "THEN " 
                +" b.status = 'MOTION_SIGNED' " 
                +" ELSE " 
                +" b.status LIKE '%%'   " 
                +" END "        
                +" ORDER BY b.oopExtractId DESC";

但是当它运行时它会产生以下异常

  

org.hibernate.hql.ast.QuerySyntaxException:意外令牌:= .....

3 个答案:

答案 0 :(得分:2)

这个也适用于Hibernate 4 / JPA和Spring 4!

flags

答案 1 :(得分:1)

我在一个工作项目中使用了以下查询。可以将它用作模板:)

@Document
public class User {
    private String name;
    private List<Address> addresses = new ArrayList<>();

    // ctr, getters, setters...

    public static class Address {
        private String city;

        public Address(String city) { 
            this.city = city;
        }

        // getters, setters...
    }
}

答案 2 :(得分:0)

请试试这个。希望它有效。

            "SELECT b FROM OOPExtract as b WHERE "
            +" b.tranStatId =" +receiptNumber+ " AND " 
            +" b.orderType IN ('EMERGENCY', 'PLENARY', 'PETITION','EXTENSION','MOTION') AND "
            **+" CASE WHEN b.orderType 'MOTION' " `enter code here`
            +  "THEN 'MOTION_SIGNED' " 
            +" ELSE "** 
            +" b.status LIKE '%%'   " 
            +" END "        
            +" ORDER BY b.oopExtractId DESC";