春季 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

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

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

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

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

P.S:所以你不需要检查是否为空,也不需要用方法从DB中提取记录。只需通过即可保存/更新记录。sample.getId()findOnesampleRepository.save(sample)


答案 2

推荐