有没有办法在不丢失旧数据的情况下插入一条新记录,如果不存在则更新记录?
这是我的服务层方法:
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 注解能否解决我的问题?
最佳答案
因为您已经在使用 Spring 和 Spring-Data-Jpa,调用 sampleRepository.save(sample);
就足够了。 save方法首先根据实体的标识值检查传入的实体是新实体还是现有实体。身份由实体的主键定义。
您还可以使用 EntityManager#merge方法。但是由于您已经在使用 Spring Data,保存方法将在内部调用合并方法。
在我看来,您不需要使用@DynamicUpdate
,除非您有太多要更新的字段,但实际上只有很少的字段被更新,并且其他表也有很多限制。
Spring BeanUtils 与对象持久化无关。它主要旨在执行 Java bean 特定操作,例如复制属性、查找 bean 的方法、获取属性描述符等。
P.S: 所以你不需要检查 sample.getId()
是否为空,也不需要使用 findOne
方法从数据库中获取记录。只需传递 sampleRepository.save(sample)
即可保存/更新记录。
关于java - Spring JPA : How to upsert without losing data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36241163/