Spring JPA: How to upsert without losing data
Asked Answered
G

2

22

Is there any way for insert a new record if doesn't exist and update the record if exist without losing old data?

This is my service layer method:

public void saveSample(Sample sample) {
    Sample samplePersistent = sample;

    if (sample.getId() != null) {
        samplePersistent = sampleRepository.findOne(sample.getId());
        Assert.notNull(samplePersistent, "Sample entity not found with id : " + sample.getId());

        samplePersistent.setLocation(sample.getLocation());
        samplePersistent.setName(sample.getName());
        samplePersistent.setType(sample.getType());
        ...
        ...

    }

    samplePersistent.cloneAuditingInfoFrom(sample);
    sampleRepository.save(sample);
}

I think this is useless way.

Can Spring BeanUtils Class or @DynamicUpdate Annotation solve my problem?

Gagman answered 26/3, 2016 at 21:35 Comment(0)
T
23

As you're already using Spring and Spring-Data-Jpa calling sampleRepository.save(sample); would suffice. save method first checks to see if the passed in entity is a new entity or an existing one based on the identity value of the entity. Identity is defined by primary keys of your entity.

You can also use EntityManager#merge method. But as you're already using Spring Data, save method will internally call the merge method.

In my opinion you don't need to use @DynamicUpdate unless you have got so many fields to be updated but only few are actually being updated and also has many constraints with other tables.

Spring BeanUtils has nothing to do with object persistence. It is mainly aimed at doing Java bean specific operations such as copying properties, finding methods of a bean, getting property descriptors etc..

P.S: So you do not need to check if sample.getId() is null or not and fetch the record from DB with findOne method. Just passing sampleRepository.save(sample) will save/update the record.

Teddy answered 27/3, 2016 at 3:8 Comment(0)
C
0

I would prefer upsert instead of @DynamicUpdate. DynamicUpdate comes with a performance overhead and locking issues in case many requests are fired at same time.

Chaffin answered 23/12, 2022 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.