原创作品,允许转载,转载时请务必标明作者信息和声明本文章==》http://www.cnblogs.com/zhu520/p/7774144.html
这边文章是接的刚刚前一遍的基础上敲的 SSH框架的多表查询和增删查改 (方法一)上
一:
现在配置你的 applicationContext.xml , web.xml 配置文件
1):applicationContext.xml --》这些配置你大概大概理解就好不要敲啊,反正我是复制的这些配置
这篇文章讲解了Spring 开启Annotation <context:annotation-config> 和 <context:component-scan>诠释及区别
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd" default-autowire="byName"> <!-- 开启注解 --> <context:annotation-config /> <!-- spring 扫描路径,注意当前工程只需要扫描dao和service,srpingmvc或者struts2注解才有变化 --> <context:component-scan base-package="zhu.dao,zhu.service" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://127.0.0.1:3306/jdbc01"> </property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql"> true </prop> <!-- 这个是有了之后,就算你再mysql没有表,运行也不会出错,因为有它会自动新建表,已存在不会新建 --> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="mappingDirectoryLocations"> <list> <value>classpath:zhu/cfg/</value> </list> </property> </bean> <!-- 配置声明式事务管理(采用注解的方式) --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 开启注解事务 --> <!-- 用注解来实现事务管理 --> <tx:annotation-driven transaction-manager="txManager"/> </beans>
2):web.xml --》这些配置你大概大概理解就好不要敲啊,反正我是复制的这些配置
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- spring启动文件路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext*.xml </param-value> </context-param> <!-- 启动spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
二:创建这些package的包(按你个人习惯)
1):先去po包下 新建实体类
创建实体之前说说一对多的情况
多表查询 1:员工和部门表 :1对多 ==》1是部门 多是员工 因为一个员工只能属于一个部门 而一部们则是可以有多个员工 2: 在po层的设置 部门表:就要设置 Set的属性来包含 员工 看: private Set<TbEmp> setEmps = new HashSet<TbEmp>(); public Set<TbEmp> getSetEmps() { return setEmps; } public void setSetEmps(Set<TbEmp> setEmps) { this.setEmps = setEmps; } 而在 员工表的设置:就要设置 部门 private TbDept tbDept; public TbDept getTbDept() { return tbDept; } public void setTbDept(TbDept tbDept) { this.tbDept = tbDept; } 3: 然后在去 cfg的文件夹下 TbDept.hbm.xml(部门)==》 class==>包含的是员工的全路径哦,不是它自己的全路径, name==>setEmps这个名称是你刚刚在 po层中部门设置 包含员工的名称 column="did"===》did===》是员工的外键哦 并且员工TbEmp.hbm.xml 的 column="did" 也要设置 did哦 反正名称必须相同 <set name="setEmps" cascade="save-update" inverse="true"> <key column="did"></key> <one-to-many class="zhu.po.TbEmp"/> </set> TbEmp.hbm.xml 员工 <many-to-one name="tbDept" class="zhu.po.TbDept" column="did" insert="false" update="false"> </many-to-one>
1:创建TbDept.java(部门表)的实体类
package zhu.po; import java.util.HashSet; import java.util.Set; //部门表 public class TbDept { private Integer did; private String dname; //部门包含员工 private Set<TbEmp> setEmps = new HashSet<TbEmp>(); public Set<TbEmp> getSetEmps() { return setEmps; } public void setSetEmps(Set<TbEmp> setEmps) { this.setEmps = setEmps; } public Integer getDid() { return did; } public void setDid(Integer did) { this.did = did; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } }
创建TbEmp.java(员工表)的实体类
package zhu.po; import java.util.Date; //员工表 public class TbEmp { private Integer eid; private String ename; private int did; private String gende; private int age; private Date workDate; private String password; //部门 private TbDept tbDept; 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 int getDid() { return did; } public void setDid(int did) { this.did = did; } public String getGende() { return gende; } public void setGende(String gende) { this.gende = gende; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getWorkDate() { return workDate; } public void setWorkDate(Date workDate) { this.workDate = workDate; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public TbDept getTbDept() { return tbDept; } public void setTbDept(TbDept tbDept) { this.tbDept = tbDept; } }
2:cfg包
创建实体类的映射文件
创建TbDept.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"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="zhu.po.TbDept" table="tbdept" catalog="jdbc01"> <id name="did" type="java.lang.Integer"> <column name="did" /> <generator class="identity" /> </id> <property name="dname" type="java.lang.String"> <column name="dname" length="8" /> </property> <!-- TbDept.hbm.xml(部门)==》 class==>包含的是员工的全路径哦,不是它自己的全路径, name==>setEmps这个名称是你刚刚在 po层中部门设置 包含员工的名称 column="did"===》did===》是员工的外键哦 。 并且员工TbEmp.hbm.xml 的 column="did" 也要设置 did哦 反正名称必须相同 --> <set name="setEmps" cascade="save-update" inverse="true"> <key column="did"></key> <one-to-many class="zhu.po.TbEmp"/> </set> </class> </hibernate-mapping>
创建TbEmp.hbm.xml (与上面的同理)
<many-to-one name="tbDept" class="zhu.po.TbDept" column="did" insert="false" update="false">
</many-to-one>
<?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"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="zhu.po.TbEmp" table="tbemp" catalog="jdbc01"> <id name="eid" type="java.lang.Integer"> <column name="eid" /> <generator class="identity" /> </id> <property name="did" type="java.lang.Integer"> <column name="did" length="12" /> </property> <property name="ename" type="java.lang.String"> <column name="ename" length="12" /> </property> <property name="age" type="java.lang.Integer"> <column name="age" /> </property> <property name="gende" type="java.lang.String"> <column name="gende" /> </property> <property name="workDate" type="java.util.Date"> <column name="workDate" length="19" /> </property> <property name="password" type="java.lang.String"> <column name="password" length="19" /> </property> <many-to-one name="tbDept" class="zhu.po.TbDept" column="did" insert="false" update="false"> </many-to-one> </class> </hibernate-mapping>
然后在 applicationContext.xml 中配置映射 TbDept.hbm.xml 和TbEmp.hbm.xml
common包
定义一个接口 里面增删查改改的方法
看这边文章讲解 ModeLDriven挺详细的 原文
但是下面我没使用 ModeLDriven 特点
dao包
EmpBaseDaoImpl.java 的创建
可以去看看这篇【Hibernate九】HQL之多表查询(一对多和多对多)文章写的挺好的 ,把Hibernate的查询写的挺详细的
package zhu.dao.imp; import java.util.Date; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import sun.launcher.resources.launcher; import zhu.dao.IEmpDaoBaseDao; import zhu.po.TbEmp; @Repository(value="EmpDao") @Transactional public class EmpBaseDaoImpl implements IEmpDaoBaseDao{ @Autowired SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession(){ return getSessionFactory().getCurrentSession(); } boolean b=false; @SuppressWarnings("unchecked") @Override public List<TbEmp> findAll() { String hql="from TbEmp c left outer join fetch c.tbDept "; Query query=getSession().createQuery(hql); List<TbEmp> lsitEmps=query.list(); // List<TbEmp> tbEmps=(List<TbEmp>) getSession().createQuery(hql); return lsitEmps; } @Override public boolean save(TbEmp t) { try { getSession().save(t); b=true; } catch (Exception e) { } return b; } /**查询一条数据还可以这样 * String hql = "FROM User WHERE id = :id"; Query query = session.createQuery(hql); query.setParameter("id", id); User user = (User) query.list().get(0); */ @Override public TbEmp findDataById(int id) { String hql="from TbEmp e left outer join fetch e.tbDept where eid= "+id; Query query=getSession().createQuery(hql); TbEmp tbEmp=(TbEmp) query.uniqueResult(); return tbEmp; } /** 删除还可以这样 * String hql = "DELETE FROM User WHERE id = :id"; Query query = session.createQuery(hql); query.setParameter("id", id); query.executeUpdate(); */ @Override public boolean delete(int id) { String hql="delete from TbEmp c where c.eid= "+id; Query query=getSession().createQuery(hql); try { query.executeUpdate(); b=true; } catch (Exception e) { } return b; } @Override public boolean update(TbEmp t) { String hql="update TbEmp set ename=:ename,did=:did,gende=:gende,age=:age,workDate=:workDate,password=:password where eid=:eid "; Query query=getSession().createQuery(hql); query.setString("ename", t.getEname()); query.setInteger("did", t.getDid()); query.setString("gende", t.getGende()); query.setInteger("age", t.getAge()); query.setDate("workDate", t.getWorkDate()); query.setString("password", t.getPassword()); query.setInteger("eid", t.getEid()); try { query.executeUpdate(); b=true; } catch (Exception e) { } return b; } /* 修改还可以这样 *1---- Query query = session.createQuery(hql); query.setParameter("name", user.getName()); query.setParameter("sex", user.isSex()); query.setParameter("birthday", user.getBirthday()); query.setParameter("balance", user.getBalance()); query.setParameter("id", user.getId()); * * * */ }
service包
EmpDaoServiceImpl.java
package zhu.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import zhu.dao.IEmpDao; import zhu.po.TbEmp; import zhu.service.ITbEmpDaoService; @Service public class EmpDaoServiceImpl implements ITbEmpDaoService { @Resource(name = "EmpDao") IEmpDao EmpDao; @Override public List<TbEmp> findAll() { return EmpDao.findAll(); } @Override public boolean save(TbEmp t) { return EmpDao.save(t); } @Override public boolean update(TbEmp t) { return EmpDao.update(t); } @Override public boolean delete(int id) { return EmpDao.delete(id); } @Override public TbEmp findDataById(int id) { return EmpDao.findDataById(id); } }
action包
之前的JDBC,我们使用jsp和servlet搭配,实现展现时,大体的过程是:
1 jsp触发action
2 servlet接受action,交给后台class处理
3 后台class跳转到其他的jsp,实现数据展现
现在使用struts2,实现过程变为
1 jsp出发action
2 struts2拦截请求,调用后台action
3 action返回结果,由不同的jsp展现数据
当login.jsp触发action时,就会向后抬发送EmpAction.action的请求,这个请求被后台拦截,交给struts.xml中配置的action处理
EmpAction.java
package zhu.action; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import org.apache.struts2.ServletActionContext; import org.springframework.beans.factory.annotation.Autowired; import zhu.common.BaseAction; import zhu.po.TbDept; import zhu.po.TbEmp; import zhu.service.ITbEmpDaoService; import zhu.utils.JsonDateValueProcessor; import com.opensymphony.xwork2.ActionContext; public class EmpAction extends BaseAction { /** * */ private static final long serialVersionUID = 1L; @Autowired public ITbEmpDaoService mysServiceImpl; TbEmp tbEmp1; //声明对象 @Override public TbEmp getModel() { if (tbEmp1 == null) { tbEmp1 = new TbEmp(); } return tbEmp1; } //登录 public String login() { HttpServletRequest request = ServletActionContext.getRequest(); if (request.getParameter("password") != null) { return "login"; } return "fail"; } //查收所有的数据 @Override public String listfindAll() { List<TbEmp> list = mysServiceImpl.findAll(); Map<String, String> map= new HashMap<String, String>(); ActionContext actionContext = ServletActionContext.getContext(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (int i = 0; i < list.size(); i++) { String dateString = sdf.format(list.get(i).getWorkDate()); map.put("data", dateString); } actionContext.put("list", list); actionContext.put("date", map.get("data")); return "findAll"; } //新增 @Override public String sava() { HttpServletRequest request = ServletActionContext.getRequest(); TbEmp emp=new TbEmp(); emp.setEname(request.getParameter("ename")); emp.setPassword(request.getParameter("password")); emp.setGende(request.getParameter("gende")); emp.setDid(Integer.parseInt(request.getParameter("did"))); emp.setAge(Integer.parseInt(request.getParameter("age"))); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = dateFormat.parse(request.getParameter("workDate")); emp.setWorkDate(date); if (mysServiceImpl.save(emp)) { return "login"; } } catch (ParseException e) { e.printStackTrace(); } return "fail"; } //查询一条数据 @Override public String findById() { HttpServletRequest request = ServletActionContext.getRequest(); Integer id = Integer.parseInt(request.getParameter("id")); tbEmp1 = mysServiceImpl.findDataById(id); ActionContext actionContext = ServletActionContext.getContext(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String dateString = sdf.format(tbEmp1.getWorkDate()); actionContext.put("tb", tbEmp1); actionContext.put("date", dateString); return "update"; } //修改数据 @Override public String update() { HttpServletRequest request = ServletActionContext.getRequest(); Integer id = Integer.parseInt(request.getParameter("eid")); tbEmp1.setEname(request.getParameter("ename")); tbEmp1.setPassword(request.getParameter("password")); tbEmp1.setGende(request.getParameter("gende")); tbEmp1.setDid(Integer.parseInt(request.getParameter("did"))); tbEmp1.setAge(Integer.parseInt(request.getParameter("age"))); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); tbEmp1.setEid(id); try { Date date = dateFormat.parse(request.getParameter("workDate")); if (mysServiceImpl.update(tbEmp1)) { return "login"; } } catch (ParseException e) { e.printStackTrace(); } return "fail"; } //删除数据 @Override public String delete() { HttpServletRequest request = ServletActionContext.getRequest(); int id = Integer.parseInt(request.getParameter("id")); if (mysServiceImpl.delete(id)) { return "login"; } return "fail"; } }
jsp
login.jsp 这里我在 EmpAction.java的登录并没有进行数据库得到判断,只是单纯的先看看跳转成功否
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>登录</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <div align="center"> <form action="emp/EmpAction!login.action" method="post"> 编号:<input type="text" name="ename"/><br/> 密码:<input type="text" name="password"/><br/> <input type="submit" value="登录"/> </form> </div> </body> </html>
emp.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'students.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <div align="center" style="height: 100px"> <table cellspacing="0" border="1"> <thead> <tr> <td>id</td> <td>编号</td> <td>年龄</td> <td>性别</td> <td>部门</td> <td>时间</td> <td>密码</td> <td>修改</td> <td>删除</td> </tr> </thead> <tbody> <c:forEach items="${list}" var="list2"> <tr> <td>${ list2.eid}</td> <td>${ list2.ename}</td> <td>${ list2.gende}</td> <td>${ list2.age}</td> <td>${ list2.tbDept.dname}</td> <td>${date }</td> <td>${ list2.password}</td> <td><a href="emp/EmpAction!findById.action?id=${ list2.eid }" >修改</a></td> <td><a href="emp/EmpAction!delete.action?id=${ list2.eid }" >删除</a></td> </tr> </c:forEach> </tbody> </table> </div> <hr/> <h1>新增。。。。</h1> <div align="center" > <form action="emp/EmpAction!sava.action" method="post"> 编号:<input type="text" name="ename"/> <br/> 密码:<input type="text" name="password"/> <br/> 时间:<input type="text" name="workDate"/> <br/> 年龄:<input type="text" name="age"/> <br/> 性别:<select name="gende"> <option value="男">男</option> <option value="女">女</option> </select> <br/> 部门:<select name="did"> <option value="1">A部门</option> <option value="2">B部门</option> </select> <br/> <input type="submit" value="新增"/> </form> </div> </body> </html>
update.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'update.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>修改。。。。</h1> <div align="center"> <form action="emp/EmpAction!update.action" method="post"> <input type="hidden" name="eid" value="${tb.eid }"/> 编号:<input type="text" name="ename" value="${tb.ename }"/><br/> 密码:<input type="text" name="password" value="${tb.password }"/><br/> 时间:<input type="text" name="workDate" value="${date }"/><br/> 年龄:<input type="text" name="age" value="${tb.age }"/><br/> 性别:<c:if test="${tb.gende=='男' }"> <select name="gende"> <option value="男">男</option> <option value="女">女</option> </select> </c:if> <c:if test="${tb.gende=='女' }"> <select name="gende"> <option value="女">女</option> <option value="男">男</option> </select> </c:if> <br/> 部门:<c:if test="${tb.did==1 }"> <select name="did" > <option value="1">A部门</option> <option value="2">B部门</option> </select> </c:if> <c:if test="${tb.did==2 }"> <select name="did" > <option value="2">B部门</option> <option value="1">A部门</option> </select> </c:if> <br/> <input type="submit" value="修改"/> </form> </div> </body> </html>
源码 链接:http://pan.baidu.com/s/1c2i02LM 密码:l8gm