我有两个实体。 User.java,DirectReport.java
User.java
*************************************
@Entity
@Table(name = "User")
@JsonInclude(Include.NON_NULL)
public class User{
.....
......
@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH,
CascadeType.REMOVE })
@JoinColumn(name = "user_code", referencedColumnName = "code")
public List<DirectReports> getDirectReports() {
return directReports;
}
public void setDirectReports(List<DirectReports> directReports) {
this.directReports = directReports;
}
}
DirectReport.java
****************************
@ManyToOne(optional=true)
@JoinColumn(name = "directreport_code", referencedColumnName = "code", insertable = false, updatable = false)
public User getDirectReport() {
return directReport;
}
public void setDirectReport(User directReport) {
this.directReport = directReport;
}
@Column(name="directreport_code")
public String getDirReportCode() {
return dirReportCode;
}
public void setDirReportCode(String dirReportCode) {
this.dirReportCode = dirReportCode;
}
数据插入子表中。 user_code列也会更新。但是directreports_code字段设置为null。任何人都可以帮忙吗?
编辑:更新数据库如下:
UserService.java
***********************************
User userVar;
DirectReports dr;
for (String str : model.getDirectReportsCode()) {
userVar = repository.findByCodeIgnoreCase(str);
System.out.println("userVar "+userVar.getCode());
dr = new DirectReports();
if (userVar != null) {
dr.setDirReportCode(userVar.getCode());
list.add(dr);
}
}
System.out.println("list " + list);
model.setDirectReports(list);
toBeApprovedModel2 = getMainRepository().save(model);
getMainRepository().flush();
postApprove(toBeApprovedModel2);
注意:model.getDirectReportsCode()是一个字符串。我正在迭代,找到相应的用户,将其添加到列表中并将其设置在模型对象中。我可以在“getMainRepository()。save(model)”中看到dirReportCode字段的值。
答案 0 :(得分:0)
在UserService.java
尝试设置userVar
对象上的dr
if (userVar != null) {
dr.setDirReportCode(userVar.getCode());
dr.setDirectReport(userVar); // <----- do this
//rest of your code
<强>更新强>
在User
实体中更改以下内容:
@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH,
CascadeType.REMOVE })
@JoinColumn(name = "user_code", referencedColumnName = "code")
public List<DirectReports> getDirectReports() {
return directReports;
}
收件人(请注意添加mappedBy
属性并删除@JoinColumn
):
@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH,
CascadeType.REMOVE }, mappedBy="directReport")
public List<DirectReports> getDirectReports() {
return directReports;
}
答案 1 :(得分:0)
我没有在服务器端构建直接报告,而是构建了客户端本身的对象并保存在其中,我面对任何问题。然而,我不知道为什么在服务器端构建对象并不起作用。