Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA: How to upsert without losing data

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?

like image 855
Arif Acar Avatar asked Mar 26 '16 21:03

Arif Acar


1 Answers

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.

like image 194
Bunti Avatar answered Sep 24 '22 08:09

Bunti