SpringMVC框架的多表查询和增删查改
必须声明本文章==》http://www.cnblogs.com/zhu520/p/7883268.html
一:
1):我的运行环境
我使用myeclipse(你也可以使用eclipse),tomcat7
jar包 放在百度云,托到文章最后有链接下载即可(其实也可以根据我之前http://www.cnblogs.com/zhu520/p/7772823.html 去弄,不需要去网上下载(但是只是对myeclipse而言,eclipse还是要到网上下载的jar包的))
2):包的情况
3):配置的文件需要applicationContext.xml和springmvc.xml,不需要struts.xml配置
可以去看篇链接讲解了SpringMVC与Struts2区别 或者这篇 http://blog.csdn.net/gstormspire/article/details/8239182/
applicationContext.xml
<?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"> <!-- 开启注解 --> <context:annotation-config /> <!-- 自动扫描 --> <context:component-scan base-package="zhu.dao,zhu.serviceSpring"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" /> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost: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.hbm2ddl.auto">update</prop> </props> </property> <property name="mappingDirectoryLocations"> <list> <value>classpath:zhu/cfg/</value> </list> </property> </bean> </beans>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name></display-name> <!-- spring的启动 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <description>spring监听器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载Spring-mvc的配置文件 --> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <init-param> <param-name>activeReverseAjaxEnabled</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <!--开启web层的注解 --> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 --> <context:component-scan base-package="zhu.webAction"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 日期转换 必须放在<mvc:annotation-driven />前面 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> <!-- 注解方式 --> <mvc:annotation-driven conversion-service="conversionService"> </mvc:annotation-driven> <!-- 配置日期转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="zhu.util.DateConverter"></bean> </set> </property> </bean> <!--实现属性自动转换层对象 --> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!--mvc配置视图解析 --> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/jsp_CRUD"></property> <property name="suffix" value=".jsp"></property> </bean> <!--跳转的时候只用写jsp名字,不用带后缀,因为默认的后缀“.jsp”,路径为“/WEB-INF/jsp” --> </beans>
4):po
EmpDeptVo.java
package zhu.po; import java.util.Date; public class EmpDeptVo { private Integer eid; //员工id private String ename; //员工编号 private int did; //部门id private boolean gende;//性别 private int age; //年龄 private Date workDate;//入职时间 private String password;//密码 private String dname;//部门名称 public EmpDeptVo(){} //用来查询数据 public EmpDeptVo(Integer eid,String ename,boolean gende ,int age,Date workDate,String password,int did,String dname ){ this.eid=eid; this.ename=ename; this.gende=gende; this.age=age; this.workDate=workDate; this.password=password; this.did=did; this.dname=dname; } 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 boolean isGende() { return gende; } public void setGende(boolean 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 String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } }
TbDept.java
package zhu.po; import java.util.HashSet; import java.util.Set; //部门表 public class TbDept { private Integer did; private String dname; 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 boolean gende; private int age; private Date workDate; private String password; 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 boolean isGende() { return gende; } public void setGende(boolean 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; } }
5):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> </class> </hibernate-mapping>
TbEmp.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.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.Boolean"> <column name="gende" /> </property> <property name="workDate" type="java.util.Date"> <column name="workDate" /> </property> <property name="password" type="java.lang.String"> <column name="password" length="19" /> </property> </class> </hibernate-mapping>
6):dao包
IEmpDao.java
package zhu.dao; import java.util.List; import zhu.po.EmpDeptVo; import zhu.po.TbEmp; public interface IEmpDao { public List<EmpDeptVo> findAll(); public TbEmp findDataById(int id); public boolean save(TbEmp t); public boolean update(TbEmp t); public boolean delete(int id); }
EmpDaoImpl.java
package zhu.dao.impl; 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 zhu.dao.IEmpDao; import zhu.po.EmpDeptVo; import zhu.po.TbEmp; @Transactional @Repository(value="empDao") public class EmpDaoImpl implements IEmpDao{ //自动注入 @Autowired SessionFactory sessionFactory; boolean b=false; //getCurrentSession()这个方法用到了事物,如果不在applicationContext.xml配置设置事物就会出错 public Session getSession(){ return sessionFactory.openSession(); } @SuppressWarnings("unchecked") @Override public List<EmpDeptVo> findAll() { String hql="select new zhu.po.EmpDeptVo(e.eid,e.ename,e.gende,e.age,e.workDate,e.password,d.did,d.dname) from TbEmp e ,TbDept d where e.did=d.did"; List<EmpDeptVo> list=getSession().createQuery(hql).list(); return list; } //select jdbc01.tbemp.*,jdbc01.tbdept.dname from jdbc01.tbemp left join jdbc01.tbdept on jdbc01.tbdept.did=jdbc01.tbemp.did where jdbc01.tbemp // .eid=15 @Override public TbEmp findDataById(int id) { String hql="from TbEmp where eid="+id; Query query=getSession().createQuery(hql); TbEmp e=(TbEmp) query.list().get(0); return e; } @Override public boolean save(TbEmp t) { try { getSession().save(t);b=true; } catch (Exception e) { } return b; } @Override public boolean update(TbEmp t) { String hql="update TbEmp set ename=:ename,gende=:gende,age=:age,workDate=:workDate,password=:password,did=:did where eid=:eid"; Query query=getSession().createQuery(hql); query.setParameter("ename", t.getEname()); query.setParameter("gende", t.isGende()); query.setParameter("age", t.getAge()); query.setParameter("workDate", t.getWorkDate()); query.setParameter("password", t.getPassword()); query.setParameter("did", t.getDid()); query.setParameter("eid", t.getEid()); try { query.executeUpdate(); b=true; } catch (Exception e) { } return b; } @Override public boolean delete(int id) { String hql="delete from TbEmp where eid=:eid"; Query query=getSession().createQuery(hql); query.setParameter("eid", id); try { query.executeUpdate(); b=true; } catch (Exception e) { } return b; } }
7):serviceSpring包
IEmpService.java
package zhu.serviceSpring; import java.util.List; import zhu.po.EmpDeptVo; import zhu.po.TbEmp; public interface IEmpService { List<EmpDeptVo> findAll(); TbEmp findDataById(int id); boolean save(TbEmp t); boolean update(TbEmp t); boolean delete(int id); }
IEmpService.java
package zhu.serviceSpring.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import zhu.dao.IEmpDao; import zhu.po.EmpDeptVo; import zhu.po.TbEmp; import zhu.serviceSpring.IEmpService; @Service public class EmpServiceImpl implements IEmpService { @Resource(name="empDao") IEmpDao empDao; @Override public List<EmpDeptVo> findAll() { // TODO Auto-generated method stub return empDao.findAll(); } @Override public TbEmp findDataById(int id) { // TODO Auto-generated method stub return empDao.findDataById(id); } @Override public boolean save(TbEmp t) { // TODO Auto-generated method stub return empDao.save(t); } @Override public boolean update(TbEmp t) { // TODO Auto-generated method stub return empDao.update(t); } @Override public boolean delete(int id) { // TODO Auto-generated method stub return empDao.delete(id); } }
8):webAction包
LoginAction.java
package zhu.webAction; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import sun.print.resources.serviceui; import zhu.po.EmpDeptVo; import zhu.po.TbEmp; import zhu.serviceSpring.impl.EmpServiceImpl; //这里的 /** * 时间的新增 必须要经过处理,因为springMVC没有没办法把字符串转换成日期类型。所以需要自定义参数绑定 * 前端控制器接收到请求后,找到注解形式的处理器适配器, * <!-- 日期转换 必须放在<mvc:annotation-driven />前面 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> <!-- 注解方式 --> <mvc:annotation-driven conversion-service="conversionService"> </mvc:annotation-driven> <!-- 配置日期转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="zhu.util.DateConverter"></bean> </set> </property> </bean> * @param emp * @return */ @Controller // 这个注解必须要加 @RequestMapping("/loginAction") public class LoginAction { @Autowired public EmpServiceImpl myeEmpServiceImpl; /* * @RequestMapping("/loginAction") 我们在类上面注解和方法上注解这样会更加的清晰, * 我们在类上标示更能清晰的知道这个路径是请求这个类,并在方法上注解比较清楚的是请求哪个方法 */ @RequestMapping("/login1") public ModelAndView login(String name,String password){ if (name!=null) { return listAll(); } return new ModelAndView("/fail"); } public ModelAndView listAll(){ List<EmpDeptVo> list=myeEmpServiceImpl.findAll(); ModelAndView mv=new ModelAndView("/login_ok1"); mv.addObject("empVo",list); return mv; } //新增数据 @RequestMapping("/save") public ModelAndView save(EmpDeptVo emp){ TbEmp tbEmp=new TbEmp(); tbEmp.setAge(emp.getAge()); tbEmp.setDid(emp.getDid()); tbEmp.setEname(emp.getEname()); tbEmp.setGende( emp.isGende() ); // request.getParameter("workDate"); tbEmp.setPassword(emp.getPassword()); tbEmp.setWorkDate(emp.getWorkDate()); if (myeEmpServiceImpl.save(tbEmp)) { return listAll(); } return new ModelAndView("/fail"); } //删除 @RequestMapping("/delete") public ModelAndView delete(int eid){ if (myeEmpServiceImpl.delete(eid)) { return listAll(); } return new ModelAndView("/fail"); } //查询一条数据 @RequestMapping("/findById") public ModelAndView findById(int eid){ TbEmp emVo=myeEmpServiceImpl.findDataById(eid); ModelAndView mView=new ModelAndView("/update"); mView.addObject("e", emVo); return mView; } //修改数据 @RequestMapping("/update") public ModelAndView update(EmpDeptVo emp){ TbEmp tbEmp=new TbEmp(); tbEmp.setAge(emp.getAge()); tbEmp.setDid(emp.getDid()); tbEmp.setEname(emp.getEname()); tbEmp.setGende( emp.isGende() ); tbEmp.setEid(emp.getEid()); tbEmp.setPassword(emp.getPassword()); tbEmp.setWorkDate(emp.getWorkDate()); if (myeEmpServiceImpl.update(tbEmp)) { return listAll(); } return new ModelAndView("/fail"); } }
8):util包
DateConverter.java
package zhu.util; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.core.convert.converter.Converter; /** * 时间处理 * @author XiaoZhu * */ public class DateConverter implements Converter<String, Date>{ @Override public Date convert(String source) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { return simpleDateFormat.parse(source); } catch (Exception e) { e.printStackTrace(); } return null; } }
9):jsp
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!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="loginAction/login1.do" method="post"> 编号:<input type="text" name="name" /><br /> 密码:<input type="text" name="password" /><br /> <input type="submit" value="登录" /> </form> </div> </body> </html>
login_ok1.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>所有数据</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" > <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="${empVo}" var="list2"> <tr> <td>${ list2.eid}</td> <td>${ list2.ename}</td> <td>${ list2.age}</td> <c:if test="${ list2.gende==false}"><td>男</td></c:if> <c:if test="${ list2.gende==true}"><td>女</td></c:if> <td>${ list2.dname}</td> <td>${ list2.workDate}</td> <td>${ list2.password}</td> <td><a href="loginAction/findById.do?eid=${list2.eid }" >修改</a></td> <td><a href="loginAction/delete.do?eid=${list2.eid }" >删除</a></td> </tr> </c:forEach> </tbody> </table> </div> <hr/> <div align="center" > <form action="loginAction/save.do" 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="0">男</option> <option value="1">女</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> <hr/> <div align="center" > <form action="loginAction/update.do" method="post"> <input type="hidden" name="eid" value="${ e.eid}"/> 编号:<input type="text" name="ename" value="${ e.ename}"/> <br/> 密码:<input type="text" name="password" value="${ e.password}"/> <br/> 时间:<input type="text" name="workDate" value="${ e.workDate}"/> <br/> 年龄:<input type="text" name="age" value="${ e.age}"/> <br/> 性别:<c:if test="${e.gende==false }"> <select name="gende"> <option value="0">男</option> <option value="1">女</option> </select> </c:if> <c:if test="${e.gende==true }"> <select name="gende"> <option value="1">女</option> <option value="0">男</option> </select> </c:if> <br/> 部门:<c:if test="${e.did==1 }"> <select name="did" > <option value="1">A部门</option> <option value="2">B部门</option> </select> </c:if> <c:if test="${e.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> <!--<input type="text" name="gende" value="${e.gende==true?'女':'男' }"><br> --> </body> </html>
效果:
下载源码:链接:http://pan.baidu.com/s/1qYQcmxm 密码:2uu7