Hibernate多对多的关系

数据库和项目工程


实体类

Roles.java

package com.minde.po;

import java.util.HashSet;
import java.util.Set;

public class Roles {

	private int roleid;
	private String rolename;
	private String memo;
	//一个角色有多个用户
	private Set<Userinfo> userinfos = new HashSet<>();
	
	public Set<Userinfo> getUserinfos() {
		return userinfos;
	}
	public void setUserinfos(Set<Userinfo> userinfos) {
		this.userinfos = userinfos;
	}
	public int getRoleid() {
		return roleid;
	}
	public void setRoleid(int roleid) {
		this.roleid = roleid;
	}
	public String getRolename() {
		return rolename;
	}
	public void setRolename(String rolename) {
		this.rolename = rolename;
	}
	public String getMemo() {
		return memo;
	}
	public void setMemo(String memo) {
		this.memo = memo;
	}
	public Roles(int roleid, String rolename, String memo) {
		super();
		this.roleid = roleid;
		this.rolename = rolename;
		this.memo = memo;
	}
	public Roles(String rolename, String memo) {
		super();
		this.rolename = rolename;
		this.memo = memo;
	}
	public Roles() {
		super();
	}
	@Override
	public String toString() {
		return "Roles [roleid=" + roleid + ", rolename=" + rolename + ", memo=" + memo + "]";
	}
	
}

Userinfo.java

package com.minde.po;

import java.util.HashSet;
import java.util.Set;

public class Userinfo {

	private int userid;
	private String username;
	private String password;
	//一个用户有多个角色
	private Set<Roles> roles = new HashSet<>();
	public Set<Roles> getRoles() {
		return roles;
	}
	public void setRoles(Set<Roles> roles) {
		this.roles = roles;
	}
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Userinfo(int userid, String username, String password) {
		super();
		this.userid = userid;
		this.username = username;
		this.password = password;
	}
	public Userinfo(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
	public Userinfo() {
		super();
	}
	@Override
	public String toString() {
		return "Userinfo [userid=" + userid + ", username=" + username + ", password=" + password + "]";
	}
	
}

hbm.xml文件配置(关系映射)

Roles.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.minde.po">
	<class name="Roles">
		<!-- 定义主键生成策略 -->
		<id name="roleid">
			<generator class="sequence">
				<param name="sequence">roles_seq</param>
			</generator>
		</id>
		<!-- 定义其它基本属性 -->
		<property name="rolename"/>
		<property name="memo"/>
		<!-- 定义多对多关联关系映射 -->
		<!-- table属性指示第三张表的表名 -->
		<set name="userinfos" table="roles_userinfo" lazy="false" >
			<!-- <key>代表当前表roles在第三张表roles_userinfo中的外键 -->
			<key column="rid"/>
			<!-- 下面的column代表对方表userinfo在第三张表中的外键 -->
			<many-to-many class="Userinfo" column="userid"/>
		</set>
	</class>
</hibernate-mapping>


首先该类的属性userinfos 所关联的表为roles_userinfo;key代表当前表roles在第三张表roles_userinfo的外键,而many-to-many 的class是代表对方的类,column代表对方表在第三张表中的外键


Userinfo.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.minde.po">
	<class name="Userinfo">
		<!-- 定义主键生成策略 -->
		<id name="userid">
			<generator class="sequence">
				<param name="sequence">sequence_userinfo</param>
			</generator>
		</id>
		<!-- 定义其它基本属性 -->
		<property name="username"/>
		<property name="password"/>
		<set name="roles" table="roles_userinfo">
			<key column="userid"/>
			<many-to-many class="Roles" column="roleid"/>
		</set>
	</class>
</hibernate-mapping>

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>
		<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
		<property name="hibernate.connection.username">scott</property>
		<property name="hibernate.connection.password">tiger</property>
		<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
		<property name="show_sql">true</property>
		<mapping resource="com/minde/po/Userinfo.hbm.xml"/>
		<mapping resource="com/minde/po/Roles.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

struts.XML文件配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<!-- 配置常量以覆盖struts-default.xml文件的默认设置 -->
	<constant name="struts.devMode" value="true"/>
	<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
	<package name="struts" extends="struts-default">
	
	</package>
</struts>

Utils包的HibernateSessionFactory.java

package com.minde.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateSessionFactory {
	/**引入sessionFactory*/
	private static SessionFactory sessionFactory;
	/**构造Configuration配置*/
	private static Configuration config = new Configuration();
	/**定义一个ThreadLocal对象用于存放session*/
	private static ThreadLocal<Session> threadLocal = new ThreadLocal<>();
	static {
		//1.读取hibernate.cfg.xml
		config.configure();
		//2.构造ServiceRegistry对象
		ServiceRegistry sr = new ServiceRegistryBuilder()
							.applySettings(config.getProperties())
							.buildServiceRegistry();
		//3.生成一个sessionFactory
		sessionFactory = config.buildSessionFactory(sr);
	}
	
	//获取到session对象
	public static Session getSession(){
		Session session = threadLocal.get();
		if(null == session || !session.isOpen()){
			if(sessionFactory == null){
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession() : null;
			//将session设置到threadLocal中
			threadLocal.set(session);
		}
		return session;
	}
	
	//重建sessionFactory
	private static void rebuildSessionFactory() {
		config.configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
										  .applySettings(config.getProperties())
										  .buildServiceRegistry();
		sessionFactory = config.buildSessionFactory(serviceRegistry );
	}
	
	//关闭session
	public static void closeSession(){
		Session session = threadLocal.get();
		threadLocal.set(null);
		if(session != null){
			session.close();
		}
	}
}

dao层

IBaseDao.java

package com.minde.dao;

import java.io.Serializable;
import java.util.List;

public interface IBaseDao {

	/** @param hql  查询所有*/
	public List findAll(String hql) ;
	
	/**@param obj 需要添加的对象 */
	public void save(Object obj);
	
	/** @param obj 需要修改的对象*/
	public void update(Object obj);
	
	/** 根据id查询对象
	 * @param clazz  要查找的对象类
	 * @param id 
	 * @return
	 */
	public Object findObjectById(Class clazz,Serializable id);
	
	/** @param obj 删除指定对象*/
	public void delete (Object obj);
}

BaseDaoImpl.java

package com.minde.dao.impl;

import java.io.Serializable;
import java.util.List;

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

import com.minde.dao.IBaseDao;
import com.minde.utils.HibernateSessionFactory;

public class BaseDaoImpl implements IBaseDao {

	@Override
	public List findAll(String hql) {
		List list = null;
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			//1.开始事务
			tx = session.beginTransaction();
			//2.执行命令
			list = session.createQuery(hql).list();
			//3.提交事务
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			//回滚事务
			tx.rollback();
		}finally{
			//关闭session
			HibernateSessionFactory.closeSession();
		}
		return list;
	}

	@Override
	public void save(Object obj) {
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			//1.开始事务
			tx = session.beginTransaction();
			//2.执行命令
			session.save(obj);
			
			//3.提交事务
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			//回滚事务
			tx.rollback();
		}finally{
			//关闭session
			HibernateSessionFactory.closeSession();
		}
	}

	@Override
	public void update(Object obj) {
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			//1.开始事务
			tx = session.beginTransaction();
			//2.执行命令
			session.merge(obj);
			//session.update(obj);
			//3.提交事务
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			//回滚事务
			tx.rollback();
		}finally{
			//关闭session
			HibernateSessionFactory.closeSession();
		}
	}

	@Override
	public Object findObjectById(Class clazz, Serializable id) {
		Object obj = null;
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			//1.开始事务
			tx = session.beginTransaction();
			//2.执行命令
			obj = session.get(clazz,id);
			//3.提交事务
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			//回滚事务
			tx.rollback();
		}finally{
			//关闭session
			HibernateSessionFactory.closeSession();
		}
		return obj;
	}

	@Override
	public void delete(Object obj) {
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			//1.开始事务
			tx = session.beginTransaction();
			//2.执行命令
			session.delete(obj);
			//3.提交事务
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			//回滚事务
			tx.rollback();
		}finally{
			//关闭session
			HibernateSessionFactory.closeSession();
		}
	}

}

RolesAction.java

package com.minde.action;

import java.util.ArrayList;
import java.util.List;

import javax.management.relation.Role;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;

import com.minde.dao.IBaseDao;
import com.minde.dao.impl.BaseDaoImpl;
import com.minde.po.Roles;
import com.minde.po.Userinfo;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("all")
@Results({@Result(name="list",location="list.jsp"),
		  @Result(name="add",location="add.jsp"),
		  @Result(name="update",location="update.jsp"),
		  @Result(name="tolist",type="redirect",location="roles!list")})
@ResultPath("/WEB-INF/roles/")
public class RolesAction extends ActionSupport {

	private IBaseDao bd = new BaseDaoImpl();
	private List<Roles> roles ;
	private List<Integer> userids;		//所有用户编号
	private List<Userinfo> userinfos;   //所有用户集合
	private Roles role;					//代表当前正在操作的role对象
	
	public Roles getRole() {
		return role;
	}

	public void setRole(Roles role) {
		this.role = role;
	}

	public List<Userinfo> getUserinfos() {
		return userinfos;
	}

	public void setUserinfos(List<Userinfo> userinfos) {
		this.userinfos = userinfos;
	}

	public List<Integer> getUserids() {
		return userids;
	}

	public void setUserids(List<Integer> userids) {
		this.userids = userids;
	}

	//列表所有的角色
	public List<Roles> getRoles() {
		return roles;
	}

	public void setRoles(List<Roles> roles) {
		this.roles = roles;
	}
	//列表角色
	public String list() throws Exception{
		roles = bd.findAll("from Roles");
		return "list";
	}
	//到添加角色页面
	public String toadd() throws Exception{
		//思考:在添加角色时考虑是否选择此角色所关联的用户?(提供用户列表)
		//查询出所有用户集合
		userinfos = bd.findAll("from Userinfo");
		return "add";
	}
	//添加用户
	public String add() throws Exception{
		for(int id : userids){
			//1.根据用户编号查询出用户
			Userinfo user = (Userinfo) bd.findObjectById(Userinfo.class, id);
			//2.建立role对象和user对象间的关系
			role.getUserinfos().add(user);
		}
		bd.save(role);
		return "tolist";
	}
	//到修改页面
	public String toupdate() throws Exception{
		//1.根据roleid得到当前role对象
		role = (Roles) bd.findObjectById(Roles.class, role.getRoleid());
		//2.根据role对象查询出其关联的userid
		userids = new ArrayList<>();
		for(Userinfo userinfo: role.getUserinfos()){
			userids.add(userinfo.getUserid());
		}
		//3.查询出用户集合
		userinfos = bd.findAll("from Userinfo");
		return "update";
	}
	//修改角色
	public String update() throws Exception{
		for(int id : userids){
			//1.根据用户编号查询出用户
			Userinfo user = (Userinfo) bd.findObjectById(Userinfo.class, id);
			//2.建立role对象和user对象间的关系(有主键才需要“你中有我,我中有你”,这里的第三张表中无主键)
			role.getUserinfos().add(user);
		}
		bd.update(role);
		return "tolist";
	}
	//删除角色
	public String delete() throws Exception{
		//1.根据roleid得到当前role对象
		role = (Roles) bd.findObjectById(Roles.class, role.getRoleid());
		//2.删除角色
		bd.delete(role);
		return "tolist";
	}
}

JSP页面

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>列表角色</title>
<script>
	function $(v){
		return document.getElementById(v);
	}
	function toggle(v){
		$('t_'+v).style.display = $('t_'+v).style.display == 'none' ? '' : 'none';
	}
</script>
</head>
<body>
	<h2>列表角色<hr></h2>
	<table width=80% align=center border=4 rules="rows">
		<tr height=40 bgcolor="#efefef">
			<th>角色ID</th><th>角色名称</th><th>角色描述</th><th>操作</th>
		</tr>
		<s:iterator value="roles">
			<tr height=36 align=center bgcolor="lightblue" οnclick="toggle(${roleid})">
				<td><s:property value="roleid"/></td>
				<td><s:property value="rolename"/></td>
				<td><s:property value="memo"/></td>
				<td>
					<s:a href="roles!toupdate?role.roleid=%{roleid}">修改</s:a>
					<s:a href="roles!delete?role.roleid=%{roleid}" οnclick="return confirm('你真的要删除吗?')">删除</s:a>
				</td>
			</tr>
			<tr style="display:none" id="t_${roleid }">
				<td colspan=4>
					<s:iterator value="userinfos">
						<div style="border:1px dotted blue;background:lightyellow">
						账号:<s:property value="userid"/><br>
						用户名:<s:property value="username"/><br>
						密码:<s:property value="password"/><br>
						</div>
					</s:iterator>
				</td>
			</tr>
		</s:iterator>
		<tr height=40 bgcolor="#efefef" align=right>
			<td colspan=4>
			<s:a href="roles!toadd">添加角色</s:a>
			明德学校版权所有2000-2017.</td>
		</tr>
	</table>
</body>
</html>

add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加角色</title>

</head>
<body>
	<h2>添加角色<hr></h2>
	<s:form action="roles!add">
		<s:textfield name="role.rolename" label="角色名称"/>
		<s:textfield name="role.memo" label="角色说明"/>
		<!-- 所有的用户信息 -->
		<s:checkboxlist list="userinfos" listKey="userid" listValue="username" 
		   name="userids" label="请选择用户"/>
		<s:submit value="添加角色"/>
	</s:form>
</body>

</html>

update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改角色</title>

</head>
<body>
	<h2>修改角色<hr></h2>
	<s:form action="roles!update">
		<s:hidden name="role.roleid"/>
		<s:textfield name="role.rolename" label="角色名称"/>
		<s:textfield name="role.memo" label="角色说明"/>
		<!-- 所有的用户信息 -->
		<s:checkboxlist list="userinfos" listKey="userid" listValue="username" 
		   name="userids" label="请选择用户"/>
		<s:submit value="修改角色" align="left"/>
	</s:form>
</body>

</html>

web.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>hibernate4_01</display-name>
    <!-- 配置struts2过滤器 -->
	<filter>
		<filter-name>struts</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值