samedi 23 juillet 2016

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?

Aucun commentaire:

Enregistrer un commentaire