hibernate一对一外键关联
程序员文章站
2022-04-18 08:06:18
...
一、创建实体类
Java代码
package com.wr.hibernate.entity; public class Department { private int deptId; private String deptName; private Manager mgr; public int getDeptId() { return deptId; } public Manager getMgr() { return mgr; } public void setMgr(Manager mgr) { this.mgr = mgr; } public void setDeptId(int deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } @Override public String toString() { return "Department [deptId=" + deptId + ", deptName=" + deptName + "]"; } }
Java代码
package com.wr.hibernate.entity; public class Manager { private int mgrId; private String mgrName; private Department dept; public int getMgrId() { return mgrId; } public void setMgrId(int mgrId) { this.mgrId = mgrId; } public String getMgrName() { return mgrName; } public void setMgrName(String mgrName) { this.mgrName = mgrName; } public Department getDept() { return dept; } public void setDept(Department dept) { this.dept = dept; } @Override public String toString() { return "Manager [mgrId=" + mgrId + ", mgrName=" + mgrName + ", dept=" + dept + "]"; } }
二、创建POJO映射文件
Xml代码
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wr.hibernate.entity"> <class name="Department" table="department" dynamic-insert="true"> <id name="deptId" type="java.lang.Integer"> <column name="dept_id" /> <generator class="native"></generator> </id> <property name="deptName" type="java.lang.String"> <column name="dept_name" /> </property> <many-to-one name="mgr" class="Manager"> <column name="mgr_id" unique="true"></column> </many-to-one> </class> </hibernate-mapping>
Xml代码
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wr.hibernate.entity"> <class name="Manager" table="manager" dynamic-insert="true"> <id name="mgrId" type="java.lang.Integer"> <column name="mgr_id" /> <generator class="native"></generator> </id> <property name="mgrName" type="java.lang.String"> <column name="mgr_name" /> </property> <one-to-one name="dept" class="Department" property-ref="mgr"> </one-to-one> </class> </hibernate-mapping>