代码结构和使用的jar包
Employee.java(省略get set方法)
package com.orange.demo; /** * 员工实体 * 员工和部门的关系是多对一 */ public class Employee { private Integer employeeId; private String employeeName; private Department department; }
Department(省略get set方法)
package com.orange.demo; import java.util.HashSet; import java.util.Set; /** * 部门实体 * 部门和员工的关系是一对多 */ public class Department { private Integer departmentId; private String departmentName; private Set<Employee> employee = new HashSet<Employee>(); }
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"> <hibernate-mapping package="com.orange.demo"> <class name="Department" table="t_department"> <id name="departmentId" column="departmentId"> <generator class="native"></generator> </id> <property name="departmentName" column="departmentName" type="string"></property> <!-- 部门和员工是一对多关系 inverse属性:默认为false,表示本方维护关联关系。如果为true,表示本方不维护关联关系。 cascade=delete 删除部门时,同时将该部门的所有员工也删除,和inverse属性无关--> <set name="employee" inverse="false" cascade="delete"> <!-- 指定需要关联的列 --> <key column="departmentId"></key> <!--需要关联的表(类) --> <one-to-many class="Employee"/> </set> </class> </hibernate-mapping>
Employee.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"> <hibernate-mapping package="com.orange.demo"> <class name="Employee" table="t_employee"> <id name="employeeId" column="employeeId"> <generator class="native"></generator> </id> <property name="employeeName" column="employeeName" type="string"></property> <!--相对于员工这一端是 多对一 --> <many-to-one name="department" class="Department" column="departmentId"></many-to-one> </class> </hibernate-mapping>
Test.java
package com.orange.demo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class Test { private static SessionFactory sessionFactory = null; static{ Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); //在src目录下 sessionFactory = cfg.buildSessionFactory(); } public static void main(String[] args) { try { save(); testGet(); // delete(); } catch (Exception e) { e.printStackTrace(); } } public static void save() throws Exception { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Department department1 = new Department(); department1.setDepartmentName("开发部"); Department department2 = new Department(); department2.setDepartmentName("测试部"); Employee employee1 = new Employee(); employee1.setEmployeeName("大橙子"); Employee employee2 = new Employee(); employee2.setEmployeeName("二橙子"); Employee employee3 = new Employee(); employee3.setEmployeeName("小王"); //为员工添加部门 employee1.setDepartment(department1); employee2.setDepartment(department1); employee3.setDepartment(department2); /*//开发部增加两名员工,大橙子和二橙子 department1.getEmployee().add(employee1); department1.getEmployee().add(employee2); //测试部增加一名员工,小王 department2.getEmployee().add(employee3);*/ session.save(department1); //需要被依赖的放在前面保存这里是员工需要依赖部门 session.save(department2); session.save(employee1); session.save(employee2); session.save(employee3); tx.commit(); session.close(); } public static void testGet() throws Exception { Session session = sessionFactory.openSession(); // 获取部门,并显示所有员工 System.out.println("---------------------通过部门找员工-----------------------"); Department department = (Department) session.get(Department.class, 1); System.out.println(department.getDepartmentName()+"有"+department.getEmployee().size()+"员工"); System.out.println(department.getEmployee());//得到的是Employee的set集合,遍历可取出所有员工信息 //获取员工,并显示所在部门 System.out.println("---------------------通过员工找部门-----------------------"); Employee employees = (Employee) session.get(Employee.class, 1); System.out.println(employees.getEmployeeName()+"在"+employees.getDepartment().getDepartmentName()); session.close(); } public static void delete() throws Exception{ Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); // 删除部门 inverse="true" 如果该部门有员工不能删除,没有才能删除 //inverse="false" 可以删除 ,删除部门后会将员工所属部门设为null Department department = (Department) session.get(Department.class, 15); session.delete(department); tx.commit(); session.close(); } }
员工和关系选择一种方法即可,结果都是一样的
employee1.setDepartment(department1);
employee2.setDepartment(department1);
employee3.setDepartment(department2);
或者:
department1.getEmployee().add(employee1);
department1.getEmployee().add(employee2);
department2.getEmployee().add(employee3);
删除部门时,这个部门可能会有员工,当inverse=true时,部门不能被删除,只有先将这个部门的员工删除后才能被删除,或者将依赖关系设置成null。
如果设置inverse=false,部门可以被删除 ,删除部门后会将该部门员工部门id设置成null
如果 Department.hbm.xml 中设置cascade="delete" (级联删除)那么删除部门时会将该部门的所有员工删除
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory name="foo"> <!-- 数据库方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/t1?characterEncoding=UTF-8</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="hibernate.connection.password">123456</property> <!-- 在控制台打印SQL,但不能打印建表语句 --> <property name="hibernate.show_sql">true</property> <!-- 打印SQL是否格式化 false:不格式化 --> <property name="hibernate.format_sql">false</property> <!--自动更新数据库结构 --> <property name="hbm2ddl.auto">update</property> <mapping resource="com/orange/demo/Department.hbm.xml"/> <mapping resource="com/orange/demo/Employee.hbm.xml"/> </session-factory> </hibernate-configuration>