繁体   English   中英

Hibernate merge where子句

[英]Hibernate merge where clause

我一直在寻找这个答案,但找不到任何能回答我问题的东西。

我正在使用Hibernate的应用程序上,它使用session.merge(object)进行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">

在执行select时会插入该语句,但是在执行merge语句时,update语句不将其作为where子句的一部分。 生成的更新类似于:

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

很好,但是我想将Hibernate模型文件中的where子句( C is null子句)也添加到where子句中,就像选择语句一样。

有谁知道我该怎么做才能将其添加到更新语句中?

谢谢您的帮助。

我认为不可能通过使用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);
    }
}

因此,我必须逐出该实体,以防止其他任何更新稍后触发更新。 然后执行更新,如果未更新任何行,则执行插入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM