Java CrudRepository:保存方法删除条目
调用Java CrudRepository:保存方法删除条目,java,spring,spring-boot,spring-data-jpa,Java,Spring,Spring Boot,Spring Data Jpa,调用crudepository.save()方法删除条目,而不是更新现有条目 控制器: @RequestMapping(value = "{id}", method = PATCH) public User update(@PathVariable Long id, @RequestBody UpdateUser existingUser) { return userService.update(existingUser); } 服务: public User update(Upda
crudepository.save()
方法删除条目,而不是更新现有条目
控制器:
@RequestMapping(value = "{id}", method = PATCH)
public User update(@PathVariable Long id, @RequestBody UpdateUser existingUser) {
return userService.update(existingUser);
}
服务:
public User update(UpdateUser existingUser) {
if (!userRepository.exists(existingUser.getId()) {
throw new UserNotFoundException();
}
UserEntity userEntity = existingUser.toEntity();
return userRepository.save(userEntity).toDto();
}
DTO:
public User {
private Long id;
private String name;
// ..
public UserEntity toEntity() {
UserEntity entity = new UserEntity();
entity.setId(id);
entity.setName(name);
return entity;
}
}
public UpdateUser extends User {
@NotNull
@Override
public Long getId() {
super.getId();
}
}
我确保在控制器和服务接收数据时在Dto上设置了ID,并且在更新后仍然相同。在任何情况下,都会出现服务
update
方法来保存和删除实体。因为我从save
方法返回的实体中返回了dto,我可以看到更改后的名称。但是,如果我刷新页面或查看users
表,条目就会消失 您总是创建一个新实体并保存它(在您的toEntity()方法中),它实际上覆盖了以前的实体
如果要更新现有用户,需要对其字段执行fetch+update,然后调用save
例如,这将更新现有用户的名称:
UserEntity userEntity = userRepository.findOneById(existingUser.getId())
userEntity.setName(newName);
userRepository.save(userEntity);
您也不应该手动设置实体的ID
和@GeneratedValue。好的,我需要找到一种更优雅的方式在DTO和实体之间进行转换。