Hibernate 映射一对一关联关系
基于外键的方式:
附上代码:
public class Manager { private Integer mgrId; private String mgrName; private Department department; public Integer getMgrId() { return mgrId; } public void setMgrId(Integer mgrId) { this.mgrId = mgrId; } public String getMgrName() { return mgrName; } public void setMgrName(String mgrName) { this.mgrName = mgrName; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
public class Department { private Integer deptId; private String deptName; private Manager manager; public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public Manager getManager() { return manager; } public void setManager(Manager manager) { this.manager = manager; } }
<hibernate-mapping> <class name="hibernate.one2one.foreign.Department" table="DEPARTMENTS"> <id name="deptId" type="java.lang.Integer"> <column name="DEPT_ID" /> <generator class="native" /> </id> <property name="deptName" type="java.lang.String"> <column name="DEPT_NAME" /> </property> <many-to-one name="manager" class="hibernate.one2one.foreign.Manager" unique="true" fetch="join"> <column name="MGR_ID"></column> </many-to-one> </class> </hibernate-mapping>
<hibernate-mapping> <class name="hibernate.one2one.foreign.Manager" table="MANAGER"> <id name="mgrId" type="java.lang.Integer"> <column name="MGR_ID" /> <generator class="native" /> </id> <property name="mgrName" type="java.lang.String"> <column name="MGR_NAME" /> </property> <one-to-one name="department" class="hibernate.one2one.foreign.Department" fetch="select" property-ref="manager"> </one-to-one> </class> </hibernate-mapping>
其中 Department 使用 many-to-one 的方式映射 Manager,但是需要设置一个 unique 属性,设置为 true,使其只能指向一个 Manager
Manager 使用 one-to-one 的方式来映射 Department,注意需要设置一个 property-ref 属性,因为其默认关联的是 Department 表中的主键,需要设置其指向 Department 哪个属性,注意,这里设置的值是域对象中的值,不是数据表中的列名。
精诚所至,金石为开。