【问题标题】:Spring JPA: How to upsert without losing dataSpring JPA:如何在不丢失数据的情况下进行更新插入
【发布时间】:2016-07-14 11:05:39
【问题描述】:

有没有办法在不存在的情况下插入新记录,如果存在则更新记录而不丢失旧数据?

这是我的服务层方法:

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);
}

我认为这是没用的方法。

Spring BeanUtils 类或@DynamicUpdate 注解能解决我的问题吗?

【问题讨论】:

    标签: java spring spring-mvc spring-boot spring-data-jpa


    【解决方案1】:

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

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

    在我看来,您不需要使用@DynamicUpdate,除非您有很多字段要更新,但实际上只有少数字段正在更新,并且对其他表也有很多限制。

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

    P.S: 所以你不需要检查sample.getId() 是否为空,并使用findOne 方法从数据库中获取记录。只需传递sampleRepository.save(sample) 即可保存/更新记录。

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 2022-12-06
      • 1970-01-01
      • 2019-06-04
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多