在hibernate的关联操作中有很多关系,其中多对一关系是最常见的。我们看这两个表。
这里有部门表和员工表。
那么我们可以这么说一个部门可以有多个员工。这就是1对多的关系。这是我们站在部门表的角度上看的。
那么我们也可以说多个员工是一个部门的,这就是多对一的关系。这就是我们站在员工表的角度上说的。
下面我做一个多对一的例子,实现两表的增加和查询操作。
1. 部门对象映射类
package com.fish.testdao;
public class Department {
private Integer id;//部门编号
private String name;//部门名称
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;
}
}
2. 员工对象映射对象类
package com.fish.testdao;
public class Employee {
private Integer id;//员工编号
private String name;//员工姓名
private Department 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;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
接着我们写一个部门的映射xml
< xml version="1.0" encoding="UTF-8" >
"-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
然后一写一个员工的映射xml
< xml version="1.0" encoding="UTF-8" >
"-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
*注
所以我一直的理解就是多对一就是通过外键来实现的。
然后我们写一个配置文件
"-//Hibernate/Hibernate Configuration DTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
com.mysql.jdbc.Driver
我们写一个测试类
package com.fish.domain;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.fish.testdao.Department;
import com.fish.testdao.Employee;
public class Test {
//写一个得到session的模板
public staticSession getMySession() {
Configurationconfiguration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactoryfactory = configuration.buildSessionFactory();
Sessionsession = factory.openSession();
returnsession;
}
//对两个表数据的添加
public staticvoid add() {
Sessionsession = getMySession();
Departmentdepartment = new Department();
department.setName("财务部");
Employeeemployee = new Employee();
employee.setName("yaku");
employee.setDepartment(department);
Transactiontransaction = session.beginTransaction();
transaction.begin();
session.save(department);
session.save(employee);
transaction.commit();
session.close();
}
//通过查员工表知道他是隶属那个部门的
public staticvoid query() {
String hql ="from Emp