以下是我的两个实体类,其中包含一对多和多对一的关系。
Parent AuditMst:
public class AuditMst implements Serializable {
/*@Id
@Column(name="AUDIT_ID")
private String auditId;*/
@Id
@Column(name="AUDIT_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private long auditId;
private String action;
@Column(name="DATE_TIME")
private Timestamp dateTime;
//bi-directional many-to-one association to AuditDetail
@OneToMany(mappedBy = "auditMst", cascade = {CascadeType.ALL })
private List<AuditDetail> auditDetails;
Child entity: Audit Details
public class AuditDetail implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@Column(name="FIELD_NAME")
private String fieldName;
//bi-directional many-to-one association to AuditMst
@ManyToOne
@JoinColumns({
@JoinColumn(name = "AUDIT_ID", referencedColumnName = "AUDIT_ID")})
private AuditMst auditMst;
当我尝试添加save audit mst和审计详细信息列表时,hibernate给了我异常:
o.h.engine.jdbc.spi.SqlExceptionHelper:Column&#39; AUDIT_ID&#39;不能为空
这是一对多关系。我正在使用spring数据jpa和hibernate。
在我的审核列表中:
AuditMst auditMst = new AuditMst();
auditMst.setAction("add");
for(Object propNameObject : map.keySet()){
AuditDetail auditDetail = new AuditDetail();
String propertyName = (String) propNameObject;
Object property1 = propUtils.getProperty(oldObject, propertyName);
Object property2 = propUtils.getProperty(newObject, propertyName);
auditDetail.setFieldName(propertyName);
auditDetail.setOldValue(property1.toString());
auditDetail.setNewValue(property2.toString);
auditDetailList.add(auditDetail);
}
auditMst.setAuditDetails(auditDetailList);
auditMstService.addAuditMst(auditMst);
ServiceImpl:
@Transactional
public AuditMst addAuditMst(AuditMst auditMst){
AuditMst savedAuditMst = auditMstRepository.save(auditMst);
}
答案 0 :(得分:0)
你有多对一的关系,然后在你的AuditDetail中将你的ManyToOne改为:
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "AUDIT_ID")
private AuditMst auditMst;
但请确保您在与实体AuditDetail相关的表中创建了列AUDIT_ID。并且由于关系是级联的,因此仅保存对象AuditMst
在你的java代码中:
AuditMst auditMst = new AuditMst();
auditMst.setAction("add");
for(Object propNameObject : map.keySet()){
AuditDetail auditDetail = new AuditDetail();
String propertyName = (String) propNameObject;
Object property1 = propUtils.getProperty(oldObject, propertyName);
Object property2 = propUtils.getProperty(newObject, propertyName);
auditDetail.setFieldName(propertyName);
auditDetail.setOldValue(property1.toString());
auditDetail.setNewValue(property2.toString);
//Here you need to add the original object to make work the on cascade.
auditDetail.setAuditMst(auditMst);
auditDetailList.add(auditDetail);
}