我有两个具有@OneToOne关系的实体:
@Entity
@Table(name="daily_report")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DailyReport {
private String rigPhone;
private DailyReportInfo dailyReportInfo;
@OneToOne(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}, optional = false)
@JoinColumn(name = "daily_report_info_id")
public DailyReportInfo getDailyReportInfo() {
return dailyReportInfo;
}
public void setDailyReportInfo(DailyReportInfo dailyReportInfo) {
this.dailyReportInfo = dailyReportInfo;
}
@Column(name = "rig_phone")
public String getRigPhone() {
return rigPhone;
}
public void setRigPhone(String rigPhone) {
this.rigPhone = rigPhone;
}
}
@Entity
@Table(name="daily_report_info")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DailyReportInfo {
private Long id;
private DailyReport dailyReport;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@JsonIgnore
@OneToOne(mappedBy = "dailyReportInfo", fetch = FetchType.LAZY)
public DailyReport getDailyReport() {
return dailyReport;
}
public void setDailyReport(DailyReport dailyReport) {
this.dailyReport = dailyReport;
}
}
我正在尝试测试仅更新对象“ DailyReportInfo”中的一个字段。
public class JacksonTest {
@Test
public void updateFromString() {
DailyReport dailyReport = new DailyReport();
dailyReport.setRigPhone("123123");
DailyReportInfo dailyReportInfo = new DailyReportInfo();
dailyReportInfo.setId(1L);
dailyReport.setDailyReportInfo(dailyReportInfo);
String json = "{\"dailyReportInfo\":{\"actualDays\":11.0}}";
ObjectMapper OBJECT_MAPPER = new ObjectMapper();
OBJECT_MAPPER.readerForUpdating(dailyReport).readValue(json);
assertThat(dailyReport.getRigPhone(), equalTo("123123")); // correct
assertThat(dailyReport.getDailyReportInfo().getId(), equalTo(1L)); // not correct = equal null, why???
}
}
但是结果是,相关对象的所有字段都被重置,并且仅添加了我发送的字段。 如何解决?我希望保留所有字段,但只更新一个已传输的字段。