【发布时间】:2017-11-29 07:49:34
【问题描述】:
我有两个实体,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>
因此,当我尝试使用级联创建一个新项目和一个新 ProjectFee 时,我收到一个错误,因为 idProject 在 db 中不能为空,并且它未设置,因为 Project 仍未创建,因此它没有 id。我知道我可以通过创建方法来解决它:
- 从项目中删除 ProjectFees
- 创建项目
- 将 ProjectFees 添加到每个项目的项目设置 idProject
- 更新项目
但这是一种“肮脏”的方式,所以我想知道是否有某种方法可以自动执行此操作
【问题讨论】:
-
在关系的两边设置引用并尝试持久化它。
-
@AbdullahKhan 问题是我不能这样做,因为我没有 Project.id,因为数据库中尚不存在项目
标签: java hibernate hibernate-mapping cross-reference