Hibernate多对多的关系

来源:互联网 发布:艾瑞咨询数据 编辑:程序博客网 时间:2024/05/20 00:13

数据库和项目工程


实体类

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();}@Overridepublic 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();}@Overridepublic 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.xmlconfig.configure();//2.构造ServiceRegistry对象ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();//3.生成一个sessionFactorysessionFactory = 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;}//重建sessionFactoryprivate static void rebuildSessionFactory() {config.configure();ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()  .applySettings(config.getProperties())  .buildServiceRegistry();sessionFactory = config.buildSessionFactory(serviceRegistry );}//关闭sessionpublic 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 {@Overridepublic 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{//关闭sessionHibernateSessionFactory.closeSession();}return list;}@Overridepublic 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{//关闭sessionHibernateSessionFactory.closeSession();}}@Overridepublic 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{//关闭sessionHibernateSessionFactory.closeSession();}}@Overridepublic 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{//关闭sessionHibernateSessionFactory.closeSession();}return obj;}@Overridepublic 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{//关闭sessionHibernateSessionFactory.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对象查询出其关联的useriduserids = 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" onclick="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}" onclick="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>
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 宝宝吃了螺丝冒怎么办 收割机滚筒皮带轮键槽滚了怎么办 微信界面变小了怎么办 拉杆箱螺丝掉了怎么办 洗衣机应急门锁没有拉绳怎么办? 奔驰glc发动机声音大怎么办 淋膜机模具螺丝拧不动怎么办 一字螺丝滑丝了怎么办 螺丝拧歪卡住了怎么办 车牌螺丝拧歪了怎么办 空心墙打膨胀螺丝打不上怎么办 沉孔内六角螺丝滑丝怎么办 内六角螺丝滑了怎么办? 三色灯不变光了怎么办 卧室灯不变色了怎么办 圆柱齿轮减速机噪音大怎么办 轴与套间隙生锈怎么办 汽车停小区被刮怎么办 下楼梯摔跤了 屁股疼 怎么办 剧烈咳嗽震的肚子疼怎么办 饺子粘在盘子上怎么办 生饺子粘在盘子怎么办 饺子粘在案板上怎么办 饺子冷冻粘起了怎么办 冰箱饺子冻住了怎么办 水饺都冻一块了怎么办 wps卸载了后文件打不开怎么办 六角螺母拧滑了怎么办 梅花内六角螺丝扭滑丝了怎么办 眼镜螺丝滑丝了怎么办 大螺丝拆不下来怎么办 一字螺丝扭不动怎么办 带帽的螺丝拧花怎么办 螺丝拧不出来了怎么办 小六角螺丝滑丝怎么办 螺丝拧不下来了怎么办 固定水龙头的螺母扭不动怎么办 小螺丝帽拧花了怎么办 6角螺丝帽拧圆了怎么办 眼镜螺丝滑扣了怎么办 眼镜的螺丝掉了怎么办