您的位置:首页 > 数据库 > MySQL

第九章 关系映射 多对一关联映射

2013-06-06 10:47 387 查看
如: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 class="native"></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对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息