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

时间:2016-03-26 21:35:38

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

如果不存在,是否有任何方法可以插入新记录,如果存在则更新记录而不会丢失旧数据?

这是我的服务层方法:

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 Class或@DynamicUpdate Annotation可以解决我的问题吗?

1 个答案:

答案 0 :(得分:5)

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

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

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

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

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