我有一个表项目与字段
ID
PROJECT_BASELINE_ATTRIBUTES_ID (FK for table PROJECT_BASELINE_ATTR)
该表具有以下映射
<hibernate-mapping package="com.initech.db.model">
<class name="com.initech.db.model.Project" table="PROJECT">
<id name="id" column="id" type="java.lang.Long">
<meta attribute="use-in-tostring">true</meta>
<generator class="sequence">
<param name="sequence">PROJECT_ID_SEQ</param>
</generator>
</id>
<many-to-one name="projectBaselineAttributes" column="PROJECT_BASELINE_ATTRIBUTES_ID" class="com.initech.db.model.ProjectBaselineAttributes" cascade="all" not-null="true">
<meta attribute="use-in-tostring">true</meta>
</many-to-one>^
</class>
</hibernate-mapping>
各自的Project.java类具有字段
private Long id;
private ProjectBaselineAttributes projectBaselineAttributes;
此外,我有一个表PROJECT_BASELINE_ATTR,其中包含以下字段
ID
Hibernate映射:
<hibernate-mapping package="com.initech.db.model">
<class name="com.initech.db.model.ProjectBaselineAttributes" table="PROJECT_BASELINE_ATTR">
<id name="id" column="id" type="java.lang.Long">
<generator class="sequence">
<param name="sequence">PRO_BASE_ATTR_ID_SEQ</param>
</generator>
</id>
<set name="projects" table="PROJECT" inverse="true" lazy="true" fetch="select">
<key>
<column name="PROJECT_BASELINE_ATTRIBUTES_ID" precision="22" scale="0" not-null="true" />
</key>
<one-to-many class="com.initech.db.model.Project" />
</set>
</class>
</hibernate-mapping>
各自的ProjectBaselineAttributes.java类具有以下字段
private Long id;
private Set projects = new HashSet();
当前的映射并不理想,因为两个表之间的关系实际上是一对一的关系,但是在ProjectBaselineAttributes中,我有一组项目,即使对于一个ProjectBaseLineattributes总是有一个Projet。 ProjectBaselineAttributes的映射应为什么样,以便我可以“单独”获取关联的Project,即,使ProjectBaselineAttributes.java类如下所示:
private Long id;
private Project project;
最佳答案
这是Hibernate documentation的部分,详细介绍了如何使用外键映射这样的双向一对一关联。
<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
<many-to-one name="address"
column="addressId"
unique="true"
not-null="true"/>
</class>
<class name="Address">
<id name="id" column="addressId">
<generator class="native"/>
</id>
<one-to-one name="person"
property-ref="address"/>
</class>
create table Person ( personId bigint not null primary key, addressId bigint not null unique )
create table Address ( addressId bigint not null primary key )