欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多对多双向关联 博客分类: hibernate HibernateJavaBeanDAOXML 

程序员文章站 2024-03-16 10:02:34
...
一个简单示例:
一个雇员可以担任几个角色,一个角色可以拥有多个雇员,雇员和角色之间存在多对多的关联关系,
在这里我们建立多对多的双向关联...



db schema:
==============================


雇员表:

CREATE TABLE [employee] (
	[eid] [int] IDENTITY (1, 1) NOT NULL ,
	[ename] [varchar] (20) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[join_date] [datetime] NOT NULL ,
	 PRIMARY KEY  CLUSTERED 
	(
		[eid]
	)  ON [PRIMARY] 
) ON [PRIMARY]
GO



角色表:

CREATE TABLE [role] (
	[roleid] [int] IDENTITY (1, 1) NOT NULL ,
	[rolename] [varchar] (20) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	 PRIMARY KEY  CLUSTERED 
	(
		[roleid]
	)  ON [PRIMARY] 
) ON [PRIMARY]
GO


雇员角色表:

CREATE TABLE [emp_role] (
	[er_id] [int] IDENTITY (1, 1) NOT NULL ,
	[er_eid] [int] NULL ,
	[er_roleid] [int] NULL ,
	 PRIMARY KEY  CLUSTERED 
	(
		[er_id]
	)  ON [PRIMARY] ,
	 FOREIGN KEY 
	(
		[er_eid]
	) REFERENCES [employee] (
		[eid]
	),
	 FOREIGN KEY 
	(
		[er_roleid]
	) REFERENCES [role] (
		[roleid]
	)
) ON [PRIMARY]
GO

Employee.java
--------------------------
package com.supersit.hibernate.bean;

import java.util.Date;
import java.util.Set;

public class Employee implements java.io.Serializable,
		com.supersit.hibernate.Interface.ObjectIn {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	//雇员编号
	private Integer eid;

	//雇员姓名
	private String ename;

	//入职时间
	private java.util.Date join_date;

	
	//角色集合
	private java.util.Set<Role> roles = new java.util.HashSet<Role>();

	public Employee(Integer eid, String ename, Date join_date) {
		this.eid = eid;
		this.ename = ename;
		this.join_date = join_date;
	}

	public Employee(Integer eid, String ename, Date join_date, Set<Role> roles) {
		this.eid = eid;
		this.ename = ename;
		this.join_date = join_date;
		this.roles = roles;
	}

	public java.util.Set getRoles() {
		return roles;
	}

	public void setRoles(java.util.Set<Role> roles) {
		this.roles = roles;
	}

	public Employee() {
	}

	public Integer getEid() {
		return eid;
	}

	public void setEid(Integer eid) {
		this.eid = eid;
	}

	public String getEname() {
		return ename;
	}

	public void setEname(String ename) {
		this.ename = ename;
	}

	public java.util.Date getJoin_date() {
		return join_date;
	}

	public void setJoin_date(java.util.Date join_date) {
		this.join_date = join_date;
	}

}




Role.java
------------------------------------
package com.supersit.hibernate.bean;

import java.util.Set;

public class Role implements java.io.Serializable,
		com.supersit.hibernate.Interface.ObjectIn {

	
	//角色编号
	private Integer roleid;

	
	//角色名称
	private String rolename;

	
	//此角色下的雇员集合
	private java.util.Set emps = new java.util.HashSet();

	public Role(Integer roleid, String rolename, Set emps) {
		this.roleid = roleid;
		this.rolename = rolename;
		this.emps = emps;
	}

	public java.util.Set getEmps() {
		return emps;
	}

	public void setEmps(java.util.Set emps) {
		this.emps = emps;
	}

	public Role() {
	}

	public Integer getRoleid() {
		return roleid;
	}

	public Role(Integer roleid, String rolename) {
		this.roleid = roleid;
		this.rolename = rolename;
	}

	public void setRoleid(Integer roleid) {
		this.roleid = roleid;
	}

	public String getRolename() {
		return rolename;
	}

	public void setRolename(String rolename) {
		this.rolename = rolename;
	}

}



配置文件:

hibernate.cfg.xml
------------------------------
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
	<property name="connection.username">sa</property>
	<property name="connection.url">
		jdbc:microsoft:sqlserver://localhost:1433;databasename=hibernate
	</property>
	<property name="dialect">
		org.hibernate.dialect.SQLServerDialect
	</property>
	<property name="connection.password">sa</property>
	<property name="connection.driver_class">
		com.microsoft.jdbc.sqlserver.SQLServerDriver
	</property>
	<property name="show_sql">true</property>
	<mapping resource="com/supersit/hibernate/mapping/Employee.hbm.xml" />
	<mapping resource="com/supersit/hibernate/mapping/Role.hbm.xml" />

</session-factory>

</hibernate-configuration>



映射文件:

Employee.hbm.xml
-----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.supersit.hibernate.bean">
	<class name="Employee" table="employee" schema="dbo"
		catalog="hibernate">
		<id name="eid" column="eid" type="int">
			<generator class="identity"></generator>
		</id>
		<property name="ename" column="ename" type="string"
			not-null="true">
		</property>
		<property name="join_date" column="join_date" type="date"></property>

		<!-- 映射roles属性,和连接表emp_role进行关联,级联方式:保存更新,检索方式:立即检索 -->
		<set name="roles" cascade="save-update" lazy="false"
			table="emp_role">

			<!-- 连接表的字段er_eid作为外键依赖于employee表的主键eid -->
			<key column="er_eid"></key>
			<!-- many-to-many属性建立和Role的多对多关联关系,class指定关联的持久化类,连接表的字段er_roleid作为外键依赖于role表的主键roleid -->
			<many-to-many class="Role" column="er_roleid"></many-to-many>
		</set>
	</class>
</hibernate-mapping>


Role.hbm.xml
----------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.supersit.hibernate.bean">
	<class name="Role" table="role" catalog="hibernate" schema="dbo">
		<id name="roleid" column="roleid" type="int">
			<generator class="identity"></generator>
		</id>
		<property name="rolename" column="rolename" type="string"
			not-null="true">
		</property>

		<set name="emps" table="emp_role" cascade="save-update"
			lazy="false" >
			<key column="er_roleid"></key>
			<many-to-many class="Employee" column="er_eid"></many-to-many>
		</set>
	</class>
</hibernate-mapping>




Dao
====================================


EmployeeDao.java
----------------------------------
package com.supersit.hibernate.dao;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.supersit.hibernate.bean.Employee;
import com.supersit.hibernate.bean.Role;
import com.supersit.hibernate.exception.HibernateMsgException;

public class EmployeeDao extends BaseDao {

	/**
	 * <p>
	 * 查询所有的雇员
	 * </p>
	 * 
	 * @author chenwei
	 * @return java.util.List
	 * @throws HibernateMsgException
	 */
	public java.util.List getEmps() throws HibernateMsgException {
		java.util.List list = new java.util.ArrayList();
		org.hibernate.Session session = null;
		org.hibernate.Transaction tran = null;
		try {
			session = com.supersit.hibernate.factory.HibernateSessionFactory
					.getSession();
			tran = session.beginTransaction();
			list = session.createQuery("from Employee e order by e.eid").list();

			tran.commit();
		} catch (Exception e) {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(session);
		}
		return list;
	}

	/**
	 * <p>
	 * 更改指定用户的角色
	 * </p>
	 * 
	 * @author chenwei
	 * @param eid:用户ID
	 * @param roleids:角色ID数组
	 * 
	 */
	public static void opeRolesOfEmp(Integer eid, String[] roleids)
			throws HibernateMsgException {
		org.hibernate.Session session = null;
		org.hibernate.Transaction tran = null;
		try {
			session = com.supersit.hibernate.factory.HibernateSessionFactory
					.getSession();
			tran = session.beginTransaction();
			Employee emp = (Employee) session.load(Employee.class, eid);
			java.util.Set roles = new java.util.HashSet();
			for (int i = 0; i < roleids.length; i++) {

				// 查询角色(此处应传入一个Session对象,否则会抛出org.hibernate.NonUniqueObjectException)
				Role role = new RoleDao().getRoleById(session, new Integer(
						roleids[i]));
				System.out.println("rolename=" + role.getRolename());
				roles.add(role);
			}
			emp.setRoles(roles);
			session.saveOrUpdate(emp);
			tran.commit();
		} catch (Exception e) {
			e.printStackTrace();
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(session);
		}
	}

	public Employee initEmp(Employee emp) throws HibernateMsgException {
		Session session = null;
		Transaction tran = null;
		try {
			session = com.supersit.hibernate.factory.HibernateSessionFactory
					.getSession();
			tran = session.beginTransaction();
			org.hibernate.Hibernate.initialize(emp.getRoles());
			session.update(emp);
			tran.commit();
		} catch (Exception e) {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(session);
		}
		return emp;
	}

	public static void main(String[] args) throws HibernateMsgException {
		// select();
		opeRolesOfEmp(new Integer(1), new String[] { "1", "3", "4" });
	}

	// 检索
	public static void select() throws HibernateMsgException {

		EmployeeDao dao = new EmployeeDao();
		List list = dao.getEmps();
		for (int i = 0; i < list.size(); i++) {
			Employee emp = (Employee) list.get(i);
			System.out.println("eid=" + emp.getEid());
			System.out.println("ename=" + emp.getEname());
			System.out.println("join_date=" + emp.getJoin_date()); //
			// 映射roles属性,lazy=false时,可以立即检索
			Set roles = emp.getRoles();
			java.util.Iterator ite = roles.iterator();
			while (ite.hasNext()) {
				Role role = (Role) ite.next();
				System.out.println("rolename=" + role.getRolename());
			}
			System.out.println("===========================================");
		}

	}

	// 保存对象
	public static void insert() throws HibernateMsgException {

		java.util.Date date = new java.util.Date();
		java.text.SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = format.parse("2007-10-17");
		} catch (ParseException e) {
			e.printStackTrace();
		}

		Employee emp = new Employee(new Integer(1), "张信哲", date);

		Session session = null;
		Transaction tran = null;
		try {
			session = com.supersit.hibernate.factory.HibernateSessionFactory
					.getSession();
			tran = session.beginTransaction();
			boolean b = new EmployeeDao().saveObj(session, emp);
			if (b) {
				System.out.println("成功保存一个Employee对象");
			}
			tran.commit();
		} catch (Exception e) {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(session);
		}

	}

}



RoleDao.java
------------------------
package com.supersit.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.supersit.hibernate.bean.Employee;
import com.supersit.hibernate.bean.Role;
import com.supersit.hibernate.exception.HibernateMsgException;

public class RoleDao extends BaseDao {

	/**
	 * <p>
	 * 根据角色ID查找角色(传入一个Session对象)
	 * </p>
	 * 
	 * @param roleid:角色ID
	 * @return com.supersit.hibernate.bean.Role
	 * @throws HibernateMsgException
	 */
	public com.supersit.hibernate.bean.Role getRoleById(Session session,
			Integer roleid) throws HibernateMsgException {
		Role role = new Role();
		try {
			java.util.List list = session.createQuery(
					"from Role r where r.roleid=:id").setInteger("id", roleid)
					.list();
			if (list != null && list.size() > 0)
				role = (Role) list.get(0);

		} catch (Exception e) {

		}
		return role;
	}

	/**
	 * <p>
	 * 根据角色ID查找角色(创建一个新的Session)
	 * </p>
	 * 
	 * @param roleid:角色ID
	 * @return com.supersit.hibernate.bean.Role
	 * @throws HibernateMsgException
	 */
	public com.supersit.hibernate.bean.Role getRoleById(Integer roleid)
			throws HibernateMsgException {
		Role role = new Role();
		Session session = null;
		Transaction tran = null;
		try {
			session = com.supersit.hibernate.factory.HibernateSessionFactory
					.getSession();
			tran = session.beginTransaction();
			java.util.List list = session.createQuery(
					"from Role r where r.roleid=:id").setInteger("id", roleid)
					.list();
			if (list != null && list.size() > 0)
				role = (Role) list.get(0);
			tran.commit();
		} catch (Exception e) {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(session);
		}
		return role;
	}

	public static void main(String[] args) throws HibernateMsgException {
		selectEmpsOfEachRole();
	}

	/**
	 * <p>
	 * 查询所有的角色
	 * </p>
	 * 
	 * @param session
	 * @return java.util.List
	 */
	public static java.util.List getAllRoles(org.hibernate.Session session) {
		java.util.List list = new java.util.ArrayList();
		list = session.createQuery("from Role r order by r.roleid asc").list();
		return list;
	}

	public static void selectEmpsOfEachRole() throws HibernateMsgException {
		org.hibernate.Session session = null;
		org.hibernate.Transaction tran = null;
		try {
			session = com.supersit.hibernate.factory.HibernateSessionFactory
					.getSession();
			tran = session.beginTransaction();
			java.util.List list = getAllRoles(session);

			for (int i = 0; i < list.size(); i++) {
				Role role = (Role) list.get(i);
				System.out.println("角色编号:" + role.getRoleid());
				System.out.println("角色名称:" + role.getRolename());
				System.out.println("此角色下的所有雇员>>>");
				java.util.Iterator ite = role.getEmps().iterator();
				while (ite.hasNext()) {
					Employee emp = (Employee) ite.next();
					System.out.println("雇员编号:" + emp.getEid());
					System.out.println("雇员姓名:" + emp.getEname());
					System.out.println("入职时间:" + emp.getJoin_date());
				}
				System.out
						.println("=======================================================");
			}
			tran.commit();

		} catch (Exception e) {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(session);
		}
	}

}








/**
 * 
 * <p>
 * 对于持久化类的添加,删除,修改可以通过继承这个类来实现 如果已开启Session缓存,可以传入这个Session对象进行相应的操作,当然也可以
 * 不调用此方法,直接调用Session对象相应的方法即可,在这里只是想实现面向接口编程
 * 对于没有开启Session缓存的情况,直接调用只有一个参数的方法,在方法体中会自动创建 Session对象,进行相关操作...
 * </p>
 * 
 * @author chenwei
 * 2007-10-26
 * 
 */
BaseDao.java
----------------------------
package com.supersit.hibernate.dao;

import org.hibernate.Session;

import com.supersit.hibernate.exception.HibernateMsgException;

public class BaseDao {

	/**
	 * <p>
	 * 保存一个com.supersit.hibernate.Interface.ObjectIn对象
	 * </p>
	 * 
	 * @author chenwei
	 * @param com.supersit.hibernate.Interface.ObjectIn
	 * @return boolean
	 * @throws HibernateMsgException
	 */
	public boolean saveObj(com.supersit.hibernate.Interface.ObjectIn in)
			throws HibernateMsgException {

		org.hibernate.Session ses = null;
		org.hibernate.Transaction tran = null;
		boolean flag = true;
		try {
			ses = com.supersit.hibernate.factory.HibernateSessionFactory1
					.getSession();
			tran = ses.beginTransaction();
			ses.save(in);
			tran.commit();
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(ses);
		}
		return flag;
	}

	/**
	 * <p>
	 * 保存一个com.supersit.hibernate.Interface.ObjectIn对象
	 * </p>
	 * 
	 * @author chenwei
	 * @param com.supersit.hibernate.Interface.ObjectIn
	 * @return boolean
	 * @throws HibernateMsgException
	 */
	public boolean saveObj(Session session,
			com.supersit.hibernate.Interface.ObjectIn in) {
		boolean flag = true;
		try {
			session.save(in);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	/**
	 * <p>
	 * 修改一个com.supersit.hibernate.Interface.ObjectIn对象
	 * </p>
	 * 
	 * @author chenwei
	 * @param com.supersit.hibernate.Interface.ObjectIn
	 * @return boolean
	 * @throws HibernateMsgException
	 */
	public boolean updateObj(com.supersit.hibernate.Interface.ObjectIn in)
			throws HibernateMsgException {
		boolean flag = true;
		org.hibernate.Session ses = null;
		org.hibernate.Transaction tran = null;
		try {
			ses = com.supersit.hibernate.factory.HibernateSessionFactory
					.getSession();
			tran = ses.beginTransaction();
			ses.update(in);
			tran.commit();
		} catch (Exception e) {
			flag = false;
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(ses);
		}
		return flag;
	}

	/**
	 * <p>
	 * 修改一个com.supersit.hibernate.Interface.ObjectIn对象
	 * </p>
	 * 
	 * @author chenwei
	 * @param com.supersit.hibernate.Interface.ObjectIn
	 * @return boolean
	 * @throws HibernateMsgException
	 */
	public boolean updateObj(Session session,
			com.supersit.hibernate.Interface.ObjectIn in) {
		boolean flag = true;
		try {
			session.update(in);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * <p>
	 * 删除一个com.supersit.hibernate.Interface.ObjectIn对象
	 * </p>
	 * 
	 * @author chenwei
	 * @param com.supersit.hibernate.Interface.ObjectIn
	 * @return boolean
	 * @throws HibernateMsgException
	 */

	public boolean deleteObj(com.supersit.hibernate.Interface.ObjectIn in)
			throws HibernateMsgException {
		boolean flag = true;
		org.hibernate.Session session = null;
		org.hibernate.Transaction tran = null;
		try {
			session = com.supersit.hibernate.factory.HibernateSessionFactory
					.getSession();
			tran = session.beginTransaction();
			session.delete(in);
			tran.commit();
		} catch (Exception e) {
			flag = false;
			com.supersit.hibernate.factory.HibernateSessionFactory
					.rollbackTran(tran);
		} finally {
			com.supersit.hibernate.factory.HibernateSessionFactory
					.closeSession(session);
		}
		return flag;
	}

	/**
	 * <p>
	 * 删除一个com.supersit.hibernate.Interface.ObjectIn对象
	 * </p>
	 * 
	 * @author chenwei
	 * @param com.supersit.hibernate.Interface.ObjectIn
	 * @return boolean
	 * @throws HibernateMsgException
	 */

	public boolean deleteObj(Session session,
			com.supersit.hibernate.Interface.ObjectIn in) {
		boolean flag = true;
		try {
			session.delete(in);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}
}



ObjectIn.java
------------------------------

package com.supersit.hibernate.Interface;

public interface ObjectIn {

}