【问题标题】:Hibernate @Formula Case statementHibernate @Formula 案例声明
【发布时间】:2013-07-24 22:12:05
【问题描述】:

我正在尝试在休眠中创建以下公式:

@Formula(value = "case when orderStatus=com.mypackage.model.OrderStatus.REJECTED then 0 else 1 ")
private int openStatus;

我得到以下异常:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 你有一个 SQL 语法错误;检查与您对应的手册 MySQL 服务器版本,以便在附近使用正确的语法 '.OrderStatus.REJECTED then 0 else 1 as formula0_ from Orders order0_ 在第 1 行按 c' 排序

公式中可以使用大小写吗?

【问题讨论】:

    标签: hibernate case formula


    【解决方案1】:

    @Formula annotation 中只允许使用常见的 SQL 代码。当 Hibernate 查询数据库时,公式将作为子选择插入。公式的值中不允许有 HQL 或 Java 代码。

    来自 Hibernate 文档:

    您可以使用 SQL 片段(也称为公式)而不是将属性映射到列。

    假设我们有一个 getter 注释:

    @Formula("(SELECT COUNT(*) from t_child c WHERE c.parent_id = parent_id)")
    public int getChildCount() {
        return childCount;
    }
    

    然后Hibernate会生成这个查询:

    SELECT this_.parent_id                        AS parent1_0_1_,
           this_.name_                            AS name2_0_1_,
    
           -- Block start
           (SELECT COUNT(*)
            FROM   t_child c
            WHERE  c.parent_id = this_.parent_id) AS formula0_1_,
           -- Block end
    
           tchild1_.parent_id                     AS parent3_3_,
           tchild1_.child_id                      AS child1_3_,
           tchild1_.child_id                      AS child1_1_0_,
           tchild1_.parent_id                     AS parent3_1_0_,
           tchild1_.name_                         AS name2_1_0_
    FROM   test.t_parent this_
           LEFT OUTER JOIN test.t_child tchild1_
                        ON this_.parent_id = tchild1_.parent_id
    WHERE  this_.parent_id =?
    

    我试图突出显示由于@Formula 注释而创建的块。希望这有助于理解 Hibernate 公式的工作原理以及公式的预期格式。

    【讨论】:

      【解决方案2】:

      我认为您必须在 SQL 查询的末尾添加一个“END”。 请尝试以下操作:

      @Formula(value = "case when orderStatus=com.mypackage.model.OrderStatus.REJECTED then 0 else 1 end")
      private int openStatus;
      

      【讨论】:

      • 我可以确认结束 END 是必要的 - 至少对于 H2 数据库。
      【解决方案3】:

      试着这样写:

      @Formula(value = "case when orderStatus='REJECTED' then 0 else 1 ")
      private int openStatus;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-24
        相关资源
        最近更新 更多