第九章 關係映射 多對一關聯映射
如:department與employee
employee中有一個department_id的外鍵
Department:
public class Department implements Serializable { private Integer id; private String name; public Department() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Employee:
public class Employee implements Serializable { private Integer id; private String name; private Department department; public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Employee() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Department.hbm.xml:(與普通的映射文件一樣)
<hibernate-mapping> <class name="cn.framelife.hibernate.entity.Department" table="department" catalog="hibernate"> <id name="id" type="java.lang.Integer"> <column name="id" /> </id> <property name="name" type="java.lang.String"> <column name="name" length="45" not-null="true" /> </property> </class> </hibernate-mapping>
Employee.hbm.xml:
<hibernate-mapping> <class name="cn.framelife.hibernate.entity.Employee" table="employee" catalog="hibernate"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator ></generator> </id> <property name="name" type="java.lang.String"> <column name="name" length="45" not-null="true" /> </property> <many-to-one name="department" column="department_id"></many-to-one> </class> </hibernate-mapping>
增加:
transaction = session.beginTransaction(); Department department = new Department(); department.setName("bb"); session.save(department); Employee employee = new Employee(); employee.setDepartment(department); employee.setName("li"); session.save(employee); transaction.commit();
查詢:
查詢employee的時候可以得到外鍵關聯的department對象。
最後更新:2017-04-03 18:52:09