原創作品,允許轉載,轉載時請務必標明作者信息和聲明本文章==》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