我正在使用与共享主键的一对一映射。
我的映射类似于 -
<class name="EmployeeDetails" table="EMPLOYEE_DETAILS" >
<cache usage="nonstrict-read-write"/>
<id name="employeeId" type="java.lang.Long">
<column name="EMPLOYEE_ID" precision="12" scale="0" />
<generator class="foreign">
<param name="property">employee</param>
</generator>
</id>
<property name="score" type="java.math.BigDecimal" update="true">
<column name="SCORE" />
</property>
<one-to-one name="employee" class="Employee" constrained="true"/>
</class>
在Employee.hbm.xml中我有
<one-to-one name="employeeDetails" class="EmployeeDetails" cascade="all,delete-orphan"></one-to-one>
我刚设置employee.setEmployeeDetails(new EmployeeDetails(score));
并试图挽救员工。
触发的查询是更新查询,但EMPLOYEE_DETAILS表中没有记录。我想要插入它。我怎样才能做到这一点?如果我使用cascade cascade =“save-update”我没有收到任何错误。如果我使用cascade =“save-update”我收到错误No row with the given identifier exists
但两次都只会触发更新查询。
答案 0 :(得分:0)
我能够像下面这样解决这个问题 -
EmployeeDetails employeeDetails= employee.getEmployeeDetails();
if(employeeDetails!= null){
employeeDetails.setScore(statusVO.getScore());
}
else {
employeeDetails = new EmployeeDetails(statusVO.getScore());
employeeDetails.setEmployee(employee);
}
employeeDetailsService.saveOrUpdate(employeeDetails);
关键是当employeeDetails存在于db(以及Employee对象中)时,只需更新属性,当它不仅设置employee对象时,hibernate将负责插入从employee对象中获取的正确id。