简体   繁体   中英

JAVA Hibernate merge is updating and not merging

When I use merge I expect that hibernate will copy not null values to a persisted entity and update the database. So in the bellow use-case, I expect that the merge will keep lastName with the value Last_0 and change firstName to the value First_1 .

but actually, hibernate is just updating, meaning that lastName become null after the code execute

    @Transactional
    public void create()  {
        SomeEntity create = new SomeEntity();
        create.setFirstName("First_0");
        create.setLastName("Last_0");
        this.getSession().save(create);
        //now in the database id:1, firstName:First_0, lastName:Last_0
   }


   @Transactional
    public void merge()  {
        SomeEntity merge = new SomeEntity();
        merge.setId(1);
        merge.setFirstName("First_1");
        this.getSession().merge(merge);
         // now in the database id:1, firstName:First_1, lastName:null
    }
    create();
    merge();

I expect lastName to be with the value of Last_0 since it is merging. but it is null.

Thanks

You are confused about how Hibernate's merge() is implemented in practice. merge() is implemented under the hood in this case via a SQL UPDATE , meaning something like the following:

UPDATE some_entity
SET
    firstName = 'First_1',
    lastName = NULL
WHERE
    id = 1;

That is, it will overwrite all the field values with whatever your detached entity happens to have. Note that if no record with this primary key id=1 existed, then Hibernate would have done an INSERT , not an update.

If you wanted to start off with the original values for the entity, then you should have used a get:

SomeEntity merge = (SomeEntity) this.getSession().get(SomeEntity.class, 1);
merge.setFirstName("First_1");
this.getSession().merge(merge);

Now the original values will "stick," except for the first name, which was overwritten to something else.

If you want hibernate to only save part of fields and not all of them use @DynamicUpdate

Example here: https://www.baeldung.com/spring-data-jpa-dynamicupdate

As posted inside:

Actually, when we use @DynamicUpdate on an entity, Hibernate does not use the cached SQL statement for the update. Instead, it will generate a SQL statement each time we update the entity. This generated SQL includes only the changed columns.

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