关键代码:
业务场景:
定义两张表:1.Manager管理者表。2.Department 部门表。两张表主键都一致,不需要外键进行管理。
详细代码:
Manager.java
package com.shuoeasy.test; public class Manager { private int id; private String name; private Department department; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } @Override public String toString() { return "Manager [id=" + id + ", name=" + name + "]"; } }
Department.java:
package com.shuoeasy.test; public class Department { private int id; private String Name; private Manager manager; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public Manager getManager() { return manager; } public void setManager(Manager manager) { this.manager = manager; } @Override public String toString() { return "Department [id=" + id + ", Name=" + Name + "]"; } }
Manager.hbm.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"> <!-- Generated 2016-6-25 14:50:51 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping> <class name="com.shuoeasy.test.Manager" table="MANAGER"> <id name="id" type="int"> <column name="ID" /> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <one-to-one name="department" class="com.shuoeasy.test.Department"> </one-to-one> </class> </hibernate-mapping>
Department.hbm.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"> <!-- Generated 2016-6-25 14:50:51 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping> <class name="com.shuoeasy.test.Department" table="DEPARTMENT"> <id name="id" type="int"> <column name="ID" /> <!-- 指定主键的生成方式 --> <generator class="foreign" > <!-- 使用manager属性 --> <param name="property">manager</param> </generator> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <!-- 采用foreign主键生成器策略的一端增加one-to-one元素映射属性, 其one-to-one节点还应增加constrained="true"属性,以便当前的主键上添加外键约束 constrained="true":增加一个外键约束 --> <one-to-one name="manager" class="com.shuoeasy.test.Manager" constrained="true" ></one-to-one> </class> </hibernate-mapping>
生成的数据库表结构:
manager表:
department表: