SSM综合案例
用员工表和部门表作为例子
先调用mybatis逆向工程插件生成mapper和service接口
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>false</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> </dependencies> </plugin>
mvc.xml配置
<!-- IoC DI 注解解析器,配置扫描控制器。说人话:让 Spring 帮我们创建控制器对象,并注入 --> <context:component-scan base-package="cn.wolfcode.controller"/> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <!-- 配置试图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <import resource="classpath:applicationContext.xml"/>
applicaationContext.xml配置
<context:property-placeholder location="classpath:db.properties"/> <bean init-method="init" destroy-method="close" class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="cn.wolfcode.domain"/> <property name="mapperLocations" value="classpath:cn/wolfcode/mapper/*Mapper.xml"/> </bean> <context:component-scan base-package="cn.wolfcode.service.impl"/> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.wolfcode.mapper"/> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
web.xml
<servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置编码过滤器, 针对 POST --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
一对多案例先写一的(Department)
dao层
在写service层
再把mapper补充一下
再写前端分发器
再写前端jsp文件
完成以上再写多的(employee)
dao层
service层
mapper
<resultMap id="BaseResultMap" type="cn.wolfcode.domain.Employee"> <id column="id" property="id" /> <result column="username" property="username" /> <result column="name" property="name" /> <result column="password" property="password" /> <result column="email" property="email" /> <result column="age" property="age" /> <result column="admin" property="admin" /> <result column="dept_id" property="dept_id" /> <result column="d_name" property="dept.name" /> </resultMap> <delete id="delete"> delete from employee where id = #{id} </delete> <insert id="insert" keyProperty="id" useGeneratedKeys="true"> insert into employee (username, name, password, email, age, admin, dept_id ) values (#{username}, #{name}, #{password}, #{email}, #{age}, #{admin}, #{dept.id} ) </insert> <update id="update"> update employee set username = #{username}, name = #{name}, password = #{password}, email = #{email}, age = #{age}, admin = #{admin}, dept_id = #{dept.id} where id = #{id} </update> <select id="selectForId" resultMap="BaseResultMap"> select id, username, name, password, email, age, admin, dept_id as d_id from employee e where e.id=#{id} </select> <select id="selectList" resultMap="BaseResultMap"> select id, username, name, password, email, age, admin, dept_id from employee </select> <sql id="where_sql"> <where> <if test="keyword != null"> AND (e.name LIKE concat('%', #{keyword}, '%') OR e.email LIKE concat('%', #{keyword}, '%')) </if> <if test="deptId != null"> AND e.dept_id = #{deptId} </if> </where> </sql> <select id="selectForCount" resultType="java.lang.Integer"> SELECT count(e.id) FROM employee e <include refid="where_sql" /> </select> <select id="selectForList" resultMap="BaseResultMap"> SELECT e.id, e.username, e.name, e.password, e.age, e.email, e.admin, e.dept_id,d.id as d_id, d.name as d_name,d.sn as d_sn FROM employee e LEFT JOIN department d ON e.dept_id = d.id <include refid="where_sql" /> LIMIT #{start}, #{pageSize} </select>
qo层
前端分发器
@Controller @RequestMapping("/employee") public class EmployeeController { @Autowired private IEmployeeService employeeService; @Autowired private IDepartmentService departmentService; @RequestMapping("/list") public String list(Model model,@ModelAttribute("qo") EmployeeQueryObject qo){ PageResult<Employee> pageResult = employeeService.query(qo); model.addAttribute("pageResult",pageResult); List<Department> departments=departmentService.selectList(); model.addAttribute("departments",departments); return "employee/list"; } @RequestMapping("/input") public String input(Long id,Model model){ List<Department> departments = departmentService.selectList(); model.addAttribute("departments",departments); if (id!=null) { Employee employee = employeeService.selectOne(id); model.addAttribute("employee",employee); } return "employee/input"; } @RequestMapping("/delete") public String delete(Long id){ if (id!=null) { employeeService.delete(id); } return "redirect:/employee/list"; } @RequestMapping("saveOrUpdate") public String saveOrUpdate(Employee employee){ if (employee.getId()==null) { employeeService.insert(employee); }else{ employeeService.update(employee); } return "redirect:/employee/list"; } }
JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!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>Insert title here</title> <script type="text/javascript"> function goPage(pageNo){ //1:获取表单对象 var form = document.forms[0]; form.currentPage.value = pageNo; form.submit(); } </script> </head> <body> <h1>员工列表</h1> <a href="/employee/input">添加</a> <form action="/employee/list" method="post"> <table border="1" cellpadding="0" cellspacing="0" width="60%"> <tr> <td colspan="7"> 关键字:<input type="text" name="keyword" value="${qo.keyword}"> 部门:<select name="deptId"> <option value="">全部</option> <c:forEach items="${departments}" var="department"> <option value="${department.id}" ${qo.deptId==department.id?'selected':''}>${department.name}</option> </c:forEach> </select> <input type="submit" value="查询"/> </td> </tr> <tr> <td>编号</td> <td>名称</td> <td>姓名</td> <td>email</td> <td>年龄</td> <td>是否管理员</td> <td>部门名称</td> <td>操作</td> </tr> <c:forEach var="employee" items="${pageResult.list}"> <tr> <td>${employee.id}</td> <td>${employee.username}</td> <td>${employee.name}</td> <td>${employee.email}</td> <td>${employee.age}</td> <td>${employee.admin ?'是':'否'}</td> <td>${employee.dept.name}</td> <td><a href="/employee/delete?id=${employee.id}">删除</a> <a href="/employee/input?id=${employee.id}">修改</a> </td> </tr> </c:forEach> <tr> <td colspan="7" align="center"> <a href="javascript:;" οnclick="goPage(1)">首页</a> <a href="javascript:;" οnclick="goPage(${pageResult.prevPage})">上一页</a> <a href="javascript:;" οnclick="goPage(${pageResult.nextPage})">下一页</a> <a href="javascript:;" οnclick="goPage(${pageResult.totalPage})">末页</a> 每页显示:<select name="pageSize" οnchange="goPage(1)"> <option value ="3" ${pageResult.pageSize == 3 ? 'selected' : ''}>3</option> <option value ="5" ${pageResult.pageSize == 5 ? 'selected' : ''}>5</option> <option value ="10" ${pageResult.pageSize == 10 ? 'selected' : ''}>10</option> </select> ${pageResult.currentPage }/${pageResult.totalPage } 页 跳转:<input type="text" name="currentPage" style="width: 30px" value="${pageResult.currentPage}"> <input type="submit" value="GO"/> </td> </tr> </table> </form> </body> </html>