简体   繁体   English

Hibernate merge where子句

[英]Hibernate merge where clause

I have looked around for this answer, but I could not find anything that answered my question. 我一直在寻找这个答案,但找不到任何能回答我问题的东西。

I am working on an application that uses Hibernate and it uses session.merge(object) to do the update or insert of the object. 我正在使用Hibernate的应用程序上,它使用session.merge(object)进行session.merge(object)的更新或插入。 The insert works fine, but the update will fail due to a unique constraint on database fields (A, B, C) if multiple records exist with the same values for (A, B). 插入工作正常,但是如果存在多个记录,且对(A,B)具有相同的值,则由于对数据库字段(A,B,C)的唯一约束,更新将失败。 The Hibernate model only has fields (A, B) defined as the id, it does not have (A, B, C) because when selecting or updating records only the record with a null value of C is wanted to be returned (C is a termination date where null means active and non-null means not active). Hibernate模型仅具有定义为id的字段(A,B),而没有(A,B,C),因为选择或更新记录时只希望返回具有空值C的记录(C为终止日期,其中null表示有效,非null表示无效。

In the Hibernate model file (Table.hbm.xml), it has a where clause defined as follows: 在Hibernate模型文件(Table.hbm.xml)中,它具有where子句,定义如下:

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

That gets inserted when doing selects, but when doing the merge statement, the update statement does not have this as part of the where clause. 在执行select时会插入该语句,但是在执行merge语句时,update语句不将其作为where子句的一部分。 The generated update is something like: 生成的更新类似于:

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

That is fine, but what I would like is to also have the where clause from the Hibernate model file (the C is null clause) to be added to the where clause like it is for select statements. 很好,但是我想将Hibernate模型文件中的where子句( C is null子句)也添加到where子句中,就像选择语句一样。

Does anyone know what I can do to get that added to the update statement? 有谁知道我该怎么做才能将其添加到更新语句中?

Thank you for your help. 谢谢您的帮助。

I do not think it is possible to update the where clause in the update statement from the merge by using the where clause from the Hibernate model. 我认为不可能通过使用Hibernate模型中的where子句从合并中更新update语句中的where子句。

What I ended up doing to solve the problem was to do something like this: 我最终要解决的问题是做这样的事情:

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);
    }
}

So I had to evict the entity to prevent any other updates from triggering an update later. 因此,我必须逐出该实体,以防止其他任何更新稍后触发更新。 Then an update was performed, and if no rows were updated, an insert is performed. 然后执行更新,如果未更新任何行,则执行插入。

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

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