【发布时间】:2021-05-06 06:33:29
【问题描述】:
我正在我的 Spring Boot 应用程序上实施 CRUD 操作,但我一直坚持实施 PUT http 请求以仅更新我的实体的某些值。特别是我的问题是我的更新方法会更新我实体中的所有字段,无论这些值是否为null。我查看了 GitHub 上做同样事情的无数项目,但我不知道什么是最好的解决方案,同时考虑到我的实体属于复杂类型,因为它们包含像 @OneToMany/@OneToOne 这样的关系。
这是我的实体类:
@Entity
@Table(name = "doctor")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Long.class)
@DynamicUpdate(value = true)
public class DoctorProfile implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 10)
private String gender;
@NotNull
@Column(unique = true, name = "phone_number", length = 15)
private String phoneNumber;
@Column(name = "specialization", length = 15)
private String specialization;
@Column(name = "avatar", length = 200)
private String avatar;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "doctor_id", nullable = false)
private Doctor doctor;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "clinic_id", nullable = false)
@JsonBackReference
private Clinic clinic;
//Getter-Setters omitted
}
这是我的服务类:
public ResponseEntity<DoctorProfile> updateDoctorProfile(DoctorProfile newInfo, long id){
DoctorProfile dc = doctorProfileRepository.findById(id).orElseThrow(
() -> new DoctorNotFoundException(id));
dc.setGender(newInfo.getGender());
dc.setPhoneNumber(newInfo.getPhoneNumber());
dc.setSpecialization(newInfo.getSpecialization());
dc.setClinic(newInfo.getClinic());
dc.setAvatar(newInfo.getAvatar());
final DoctorProfile updatedDoctor = doctorProfileRepository.save(dc);
return ResponseEntity.ok(updatedDoctor);
}
[@RestController省略类]
如您所见,我尝试使用@DynamicUpdate 注释,它应该保持@RequestBody 中所有null 字段不变,但这对我不起作用。
我还考虑实现一个逻辑,检查@RequestBody 中的字段是否为空,并最终替换它们,从我尝试更新的实体中复制值。但是这个解决方案有两个问题:
• 代码看起来很脏;
•我不能真正更新由@OneToOne 到@RequestBody 等关系引用的值,比如我的@Entity 中的Clinic 或Doctor 字段,因为我没有通过整个班级,而只是通过了ID,而这方法适用于 mysql,但不适用于 Spring JPA(我仍在尝试找出解决方案)。
我在这里阅读了一些关于堆栈溢出的答案,有些人建议创建一次只更新一个字段的方法,因为这就是 HTTP.PUT 请求的工作方式。但这真的是一个好方法吗?如果我有 100,200 甚至更多列怎么办?对我来说似乎不切实际和重复。
【问题讨论】:
标签: java spring hibernate jpa jackson