我有两个实体Project和ProjectFee:
public class Project implements Serializable {
private Integer id;
//some more fields
private Set<ProjectFees> fees = new LinkedHashSet<>();
}
public class ProjectFee implements Serializable {
//some more fields
private Integer idProject; //id of the Project ProjectFee is related to
}
映射为:
<class name="com.package.Project" table="project">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<!-- more fields -->
<set name="fees" table="project_fees" cascade="all" fetch="join" lazy="false">
<key>
<column name="id_project"/>
</key>
<one-to-many class="com.package.ProjectFees"/>
</set>
</class>
<class name="com.package.ProjectFees" table="project_fees">
<!-- more fields -->
<property name="idProject" type="java.lang.Integer">
<column name="id_project" />
</property>
</class>
因此,当我尝试使用级联创建一个新的Project和一个新的ProjectFee时,我收到一个错误,因为idProject在db中不能为null,并且由于尚未创建Project所以它没有id,所以未设置它。我知道我可以通过在create方法上解决此问题:
但这是一种“肮脏”的方式,所以我想知道是否有某种方式可以自动执行此操作
最佳答案
将您的ProjectFees
映射更改为此:
<many-to-one name="idProject" class="com.gesmifid2.common.model.Project">
<column name="id_project" />
</many-to-one>
编辑:
您的ProjectFee类应如下所示:
public class ProjectFee implements Serializable {
//some more fields
private Project project; //project ProjectFee is related to
}
并且,每次将新的
ProjectFee
添加到Project
时,都应在Project
中设置该ProjectFee
。 Project
类中的方法示例:public void addProjectFee( ProjectFee pf){
fees.add(pf);
pf.setProject(this);
}