Hibernate_4_部門與員工實例_一對多、多對一關聯關係

SessionFactoryTools類與上例相同。
1)	/**
 	 * 部門類
     * @author A_shun
 	 *
   */
public class Department {
	private Integer id;
	private String name;
	//實例化一個集合員工類
	private Set<Employee> employees = new HashSet<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;
	}

	public Set<Employee> getEmployees() {
		return employees;
	}

	public void setEmployees(Set<Employee> employees) {
		this.employees = employees;
	}

	//重寫同String函數
	public String toString() {
		return "Department [id=" + id + ", name=" + name + "]";
	}
 }
2)  /**
 *  員工類
 * @author A_shun
   	 *
 	*/
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;
	}

	//重新同toString函數
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}
 }
3)  /**
 * 員工類和部門類的持久層類
 * 
 * @author A_shun
 * 
 */
public class EmpAndDepDao {
	/**
	 * save的方法
	 */
	@Test
	public void save() {
		Session session = SessionFactoryTools.getSession();// 獲取一個session
		Transaction tx = null;// 聲明一個事務
		try {
			tx = session.beginTransaction();// 開始一個事務

			// ============================================
			// 新建部門對象,設置並設置部門名稱
			Department department = new Department();
			department.setName("開發部");

			// 新建兩個員工對象,並設置姓名
			Employee employee1 = new Employee();
			employee1.setName("趙");
			Employee employee2 = new Employee();
			employee2.setName("錢");

			// 將部門添加到員工類的中
			employee1.setDepartment(department);
			employee2.setDepartment(department);

			// 將員工對象添加到部門類中
			department.getEmployees().add(employee1);
			department.getEmployees().add(employee2);

			// 保存對象
			session.save(employee1);
			session.save(employee2);
			session.save(department);
			// ===============================================

			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null) {
				tx.rollback();
			}
			throw e;
		} finally {
			session.close();
		}
	}

	/**
	 * getById
	 */
	@Test
	public void getById() {
		Session session = SessionFactoryTools.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			// ==================================================
			// 獲取部門信息
 <span style="white-space:pre">			</span> Department department = (Department)session.get(Department.class,1);
			// 顯示部門完整的信息
			System.out.print(department + ": ");
			System.out.println(department.getEmployees());

			// 獲取員工的信息
		Employee employee = (Employee) session.get(Employee.class, 1);
			// 顯示員工的完整信息
			System.out.print(employee + ": ");
			System.out.println(employee.getDepartment());
			// ==================================================
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	/**
	 * 解除關聯關係
	 * 
	 * @throws Exception
	 */
	@Test
	public void testRemoveRelation() throws Exception {
		Session session = SessionFactoryTools.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			// =============================================
			// 從員工方解除
		<span style="white-space:pre">	</span>Employee employee = (Employee) session.get(Employee.class, 10);
			employee.setDepartment(null);

			// 從部門方解除(與inverse有關係,爲false時可以解除)
  <span style="white-space:pre">			</span>Department department = (Department)session.get(Department.class, 5);
			department.getEmployees().clear();
			// =================================================

			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null) {
				tx.rollback();
			}
			throw e;
		} finally {
			session.close();
		}
	}

	/**
	 * 刪除對象,對關聯對象的影響
	 * 
	 * @throws Exception
	 */
	@Test
	public void testDelete() throws Exception {
		Session session = SessionFactoryTools.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			// ==================================================
			// 刪除員工方(多方),對對方沒有影響
		<span style="white-space:pre">	</span>Employee employee = (Employee) session.get(Employee.class, 1);
			session.delete(employee);

			/**
			 * 刪除部門方(一方) a, 如果沒有關聯的員工:能刪除 b,
			 * 如果有關聯的員工且inverse=true,由於不能維護關聯關係,
<span style="white-space:pre">			</span> * 所以當直接執行刪除時,就會有異常 ,
			 * 如果有關聯的員工且inverse=false,由於可以維護關聯關係,
<span style="white-space:pre">			</span> * 他就會先把關聯的員工的外鍵列設爲null值,再刪除自己。
			 */
<span style="white-space:pre">			</span>Department department=(Department)session.get(Department.class,1);
			session.delete(department);
			// =================================================
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null) {
				tx.rollback();
			}
			throw e;
		} finally {
			session.close();
		}
	}
}

4)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="map_1">
	<!--類名:Department 
		類對應的表名:department 
		員工爲集合類型 、員工的表名:employees 
		關聯關係爲:cascade全關聯 
		維護關係爲:本類不維護、有對方維護
		外鍵名稱:departmentId
		映射的表名稱爲:Employee
	-->
	<class name="Department" table="department">

		<id name="id" type="int" column="id">
			<generator class="native" />
		</id>
	  <property name="name" type="string" column="name" length="20" />

		<set name="employees" cascade="all" inverse="true">
			<key column="departmentId"></key>
			<one-to-many class="Employee" />
		</set>

	</class>
</hibernate-mapping>

5)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="map_1">
	<!--類名:Employee 
		類對應的表名:employees 
		維護關係爲:本類維護
		對應列的名稱:departmentId
		映射的類名爲:Department
		映射的表名稱爲:department
	-->
	<class name="Employee" table="employees">

		<id name="id" type="int" column="id">
			<generator class="native" />
		</id>
		<property name="name" type="string" column="name" length="20" />
		
		<many-to-one name="department" class="Department" 
			column="departmentId" ></many-to-one>

	</class>
</hibernate-mapping>

6)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:///hibernate0</property>
		<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
		<property name="connection.username">root</property>
		<property name="hibernate.connection.password">root</property>

		<!-- 其他配置 -->
		<property name="hibernate.show_sql">false</property>
		<property name="hibernate.format_sql">false</property>
		<property name="hbm2ddl.auto">update</property>

		<!-- 映射文件配置 -->
		<mapping resource="map_1/Department.hbm.xml" />
		<mapping resource="map_1/Employee.hbm.xml" />

	</session-factory>
</hibernate-configuration>








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章