简体   繁体   中英

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. 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). 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).

In the Hibernate model file (Table.hbm.xml), it has a where clause defined as follows:

<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. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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