java Spring JPA:如何在不丢失数据的情况下进行更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36241163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:07:46  来源:igfitidea点击:

Spring JPA: How to upsert without losing data

javaspringspring-mvcspring-bootspring-data-jpa

提问by Arif Acar

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?

Spring BeanUtils Class 或 @DynamicUpdate Annotation 可以解决我的问题吗?

回答by Bunti

As you're already using Spring and Spring-Data-Jpa calling sampleRepository.save(sample);would suffice. savemethod 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.

由于您已经在使用 Spring,因此调用 Spring-Data-JpasampleRepository.save(sample);就足够了。save方法首先根据实体的标识值检查传入的实体是新实体还是现有实体。身份由实体的主键定义。

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

您还可以使用EntityManager#merge方法。但是由于您已经在使用 Spring Data,因此 save 方法将在内部调用 merge 方法。

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

在我看来,@DynamicUpdate除非您有这么多字段要更新,但实际上只有少数字段要更新,并且其他表也有很多约束,否则您不需要使用。

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

Spring BeanUtils 与对象持久化无关。它主要是针对 Java bean 进行特定的操作,例如复制属性、查找 bean 的方法、获取属性描述符等。

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

PS:所以您不需要检查是否sample.getId()为空并使用findOne方法从数据库中获取记录。只是通过sampleRepository.save(sample)将保存/更新记录。