【问题标题】:Hibernate merge where clauseHibernate 合并 where 子句
【发布时间】:2016-11-11 21:01:37
【问题描述】:

我四处寻找这个答案,但找不到任何回答我的问题的东西。

我正在开发一个使用 Hibernate 的应用程序,它使用 session.merge(object) 来更新或插入对象。插入工作正常,但如果存在多个具有相同值的(A,B)记录,则由于数据库字段(A,B,C)的唯一约束,更新将失败。 Hibernate 模型只有定义为 id 的字段 (A, B),它没有 (A, B, C),因为在选择或更新记录时,只希望返回具有空值 C 的记录(C 是终止日期,其中 null 表示有效,非 null 表示无效)。

在Hibernate模型文件(Table.hbm.xml)中有一个where子句定义如下:

<class name="..." table="..." lazy="true" batch-size="10" where="C is null">

在执行选择时会插入,但在执行合并语句时,更新语句不会将其作为 where 子句的一部分。生成的更新类似于:

update table
set ...
where A=?
and B=?

这很好,但我希望将 Hibernate 模型文件中的 where 子句(C is null 子句)添加到 where 子句中,就像 select 语句一样。

有谁知道我可以做些什么来将它添加到更新语句中?

感谢您的帮助。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    我认为使用 Hibernate 模型中的 where 子句无法从合并中更新 update 语句中的 where 子句。

    我最终解决问题的方法是这样做:

    void update(EntityName entity){
        session.evict(entity);
        Query update = session.createSQLQuery(
              "update table_name "
            + "set c1 = ?,"
            +     "c2 = ? "
            + "where A = ? "
            + "and B = ? "
            + "and C is null" //this was the line that was needing to be added
        );
    
        //set the parameter values
    
        if(update.executeUpdate() == 0){
            session.save(entity);
        }
    }
    

    所以我不得不驱逐实体以防止任何其他更新稍后触发更新。然后执行更新,如果没有更新行,则执行插入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-22
      • 2019-09-30
      • 2014-10-03
      • 2020-06-19
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多