如何在hibernate中表达式时使用case

时间:2016-12-20 12:27:42

标签: java hibernate hql

在HQL中,我使用了以下查询。

queryBuilder.append("SELECT cc FROM com.atulsia.core.model.CoupenCode as cc WHERE cc.segment.id = -1 or "
                    +" ( CASE WHEN (cc.category.id == "+product.getCategory().getId()+") THEN cc.subCategory.id = -1  ELSE NULL  END ) or"
                    +" cc.subCategory.id = "+product.getSubCategory().getId()+" and cc.status.statusId = 9");

但我得到例外。

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: =

先谢谢

1 个答案:

答案 0 :(得分:0)

您的HQL查询有两个错误:

queryBuilder.append(
    "SELECT cc FROM com.atulsia.core.model.CoupenCode as cc 
    WHERE cc.segment.id = -1 or "
    +" ( CASE WHEN (cc.category.id == "+product.getCategory().getId()+") THEN cc.subCategory.id = -1  ELSE NULL  END ) or"
    +" cc.subCategory.id = "+product.getSubCategory().getId()+" and cc.status.statusId = 9");

HQL中的等值与SQL相同,因此您必须使用一个=而不是==

第二个:

CASE WHEN (cc.category.id == "+product.getCategory().getId()+")
THEN cc.subCategory.id = -1 <--- You can't assign here

and in ELSE you put NULL.

不一致

<强>解决方案

    "SELECT cc FROM com.atulsia.core.model.CoupenCode as cc " +
    " WHERE cc.segment.id = -1 or " +
    "cc.subCategory.id = " +
        " (CASE " + 
           " WHEN (cc.category.id = "+product.getCategory().getId() + ")" +
           " THEN -1 ELSE cc.subCategory.id  END ) or " +
    " cc.subCategory.id = "+product.getSubCategory().getId()+ " and cc.status.statusId = 9"