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