springmvc详解(二):springmvc和mybatis整合
目录
springmvc详解(二):springmvc和mybatis整合
3.1.2、dao层spring配置文件applicationContext-dao.xml
3.2.1、service层spring配置文件applicationContext-dao.xml
3.2.2、spring管理事务的配置文件applicationContext-transaction.xml
一、环境准备
1.1、案例需求
使用springmvc和mybatis完成商品列表查询。
1.2、导入jar包
参照springmvc详解(一):入门程序这篇博客中的2.2部分。
1.3、工程结构
二、整合思路
springmvc+mybaits的系统架构:
Spring在进行管理时,是很有条理的,每个层都由Spring管理。对于表现层,通过spring管理表现层Handler;对于业务层,通过spring管理业务层service;对于持久层,通过spring管理持久层的mapper。同时遵循外层向里的调用逻辑:Handler中可以调用service接口,service中可以调用mapper接口。
整合步骤为:
第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
第二步:整合service层
通过spring管理 service接口。使用注解或配置方式将service接口配置在spring配置文件中。
实现事务控制
第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。
三、三层整合
3.1、整合dao层
3.1.1、mybatis配置文件
在mybatis自己的配置文件sqlMapConfig.xml中实现别名定义、缓存设置等配置。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局setting配置,根据需要添加 -->
<!-- 配置别名 -->
<typeAliases>
<!-- 批量扫描别名 -->
<package name="cn.itcast.ssm.po"/>
</typeAliases>
<!-- 配置mapper
由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
必须遵循:mapper.xml和mapper.java文件同名且在一个目录
-->
</configuration>
3.1.2、dao层spring配置文件applicationContext-dao.xml
在applicationContext-dao.xml中完成数据源、SqlSessionFactory、mapper扫描器的配置。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
</bean>
<!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录 中
自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名
如果扫描多个包,每个包中间使用半角逗号分隔
注意:jdk1.7和spring3的jar包兼容,jdk1.8及以上和spring3的jar包不兼容!和spring4的jar包兼容
-->
<property name="basePackage" value="cn.itcast.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
3.2、整合service层
3.2.1、service层spring配置文件applicationContext-service.xml
在applicationContext-service.xml中管理service接口实现类的bean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 商品管理的service -->
<!-- <bean id="itemsService" class="cn.itcast.ssm.service.impl.ItemsServiceImpl"></bean> -->
<context:component-scan base-package="cn.itcast.ssm.service.impl"></context:component-scan>
</beans>
3.2.2、spring管理事务的配置文件applicationContext-transaction.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 事务管理器:对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源:dataSource在applicationContext-dao.xml配置了 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(*
cn.itcast.ssm.service.impl.*.*(..))"/>
</aop:config>
</beans>
3.3、配置springmvc的配置文件
springmvc是spring的一个模块,不需要整合,但也需要在springmvc.xml中配置Handler、处理器映射器、适配器、视图解析器。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 配置Handler -->
<!-- 对于注解的Handler可以单个配置
实际开发中建议使用组件扫描
-->
<!-- <bean class="cn.itcast.ssm.controller.ItemsController3" /> -->
<!-- 可以扫描controller、service、...这里让扫描controller,指定controller的包-->
<context:component-scan base-package="cn.itcast.ssm.controller"></context:component-scan>
<!--注解映射器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
<!--注解适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
<!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
mvc:annotation-driven默认加载很多的参数绑定方法,
比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
实际开发时使用mvc:annotation-driven
-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器
解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包
-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.4、配置web.xml文件
在web.xml文件中完成一下几件事:
1、配置springmvc的前端控制器(加载springmvc配置文件)
2、加载spring的配置文件
3、加载监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>springmvcfirst</display-name>
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>
<!-- 监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springmvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等)
如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml)
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析
第二种:/,所有访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让
DispatcherServlet进行解析
使用此种方式可以实现 RESTful风格的url
第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,
仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。
-->
<url-pattern>*.action</url-pattern>
</servlet-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>
3.5、三层整合配置文件总结
3.5.1、dao层
1、mybatis自己的配置文件sqlMapConfig.xml
实现别名定义、缓存设置等配置。
2、dao层spring配置文件applicationContext-dao.xml
完成数据源、SqlSessionFactory、mapper扫描器的配置。
3.5.2、service层
1、service层spring配置文件applicationContext-service.xml
管理service接口实现类的bean(注解方式)
2、spring管理事务的配置文件applicationContext-transaction.xml
实现事务控制、AOP
3.5.3、表现层配置文件springmvc.xml
配置Handler、处理器映射器、适配器、视图解析器。
3.5.4、web.xml文件
配置springmvc的前端控制器(加载springmvc配置文件)、加载spring的配置文件、加载监听器
四、三层代码编写
4.1、dao层
4.1.1、逆向工程生成单表的po类及mapper
参照博客:MyBatis详解:逆向工程自动生成代码
4.1.2、手动定义多表的po类和mapper
针对综合查询mapper,一般情况会有关联查询,建议自定义po类和mapper,一般多表的po类继承自主表,次表以属性形式加载在po类中。
po类:ItemsCustom.java
这里仍是单表,多表的话在其中增加扩展属性即可。
package cn.itcast.ssm.po;
public class ItemsCustom extends Items {
//添加商品信息的扩展属性
}
ItemsQueryVo.java
package cn.itcast.ssm.po;
public class ItemsQueryVo {
//商品信息
private Items items;
//为了系统 可扩展性,对原始生成的po进行扩展
private ItemsCustom itemsCustom;
public Items getItems() {
return items;
}
public void setItems(Items items) {
this.items = items;
}
public ItemsCustom getItemsCustom() {
return itemsCustom;
}
public void setItemsCustom(ItemsCustom itemsCustom) {
this.itemsCustom = itemsCustom;
}
}
mapper.xml
在其中定义操作数据库的sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.itcast.ssm.mapper.ItemsMapperCustom" >
<!-- 定义商品查询的sql片段,就是商品查询条件 -->
<sql id="query_items_where">
<!-- 使用动态sql,通过if判断,满足条件进行sql拼接 -->
<!-- 商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 -->
<if test="itemsCustom!=null">
<if test="itemsCustom.name!=null and itemsCustom.name!=''">
items.name LIKE '%${itemsCustom.name}%'
</if>
</if>
</sql>
<!-- 商品列表查询 -->
<!-- parameterType传入包装对象(包装了查询条件)
resultType建议使用扩展对象
-->
<select id="findItemsList" parameterType="cn.itcast.ssm.po.ItemsQueryVo"
resultType="cn.itcast.ssm.po.ItemsCustom">
SELECT items.* FROM items
<where>
<include refid="query_items_where"></include>
</where>
</select>
</mapper>
mapper.java
在其中定义对应sql语句的抽象方法
package cn.itcast.ssm.mapper;
import cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.ItemsCustom;
import cn.itcast.ssm.po.ItemsExample;
import cn.itcast.ssm.po.ItemsQueryVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ItemsMapperCustom {
//商品查询列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
}
4.2、service层
4.2.1、service接口
package cn.itcast.ssm.service;
import java.util.List;
import cn.itcast.ssm.po.ItemsCustom;
import cn.itcast.ssm.po.ItemsQueryVo;
public interface ItemsService {
//商品查询列表
public List<ItemsCustom> findTtemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}
4.2.2、service接口实现类
还记得外层向里的调用逻辑吗?:Handler中可以调用service接口,service中可以调用mapper接口。
由于service要调用mapper,故需要在service接口实现类中注入mapper代理对象
package cn.itcast.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.itcast.ssm.mapper.ItemsMapperCustom;
import cn.itcast.ssm.po.ItemsCustom;
import cn.itcast.ssm.po.ItemsQueryVo;
import cn.itcast.ssm.service.ItemsService;
@Service("itemsService")
public class ItemsServiceImpl implements ItemsService{
@Autowired
private ItemsMapperCustom itemsMapperCustom;
@Override
public List<ItemsCustom> findTtemsList(ItemsQueryVo itemsQueryVo) throws Exception {
return itemsMapperCustom.findItemsList(itemsQueryVo);
}
}
4.3、表现层
4.3.1、编写Controller(就是Handler)
由于表现层handler要调用service接口,故需要在handler中注入service接口。
package cn.itcast.ssm.controller;
import java.util.ArrayList;
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 cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.ItemsCustom;
import cn.itcast.ssm.service.ItemsService;
//商品的controller
@Controller
public class ItemsController {
@Autowired
private ItemsService itemsService;
//商品查询列表
//@RequestMapping实现 对queryItems方法和url进行映射,一个方法对应一个url
//一般建议将url和方法写成一样
@RequestMapping("/queryItems")
public ModelAndView quertItems() throws Exception{
//调用service查找 数据库,查询商品列表,这里使用静态数据模拟
List<ItemsCustom> itemsList = itemsService.findTtemsList(null);
//返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
//相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList);
//指定视图
//下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
//modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
//上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
modelAndView.setViewName("items/itemsList");
return modelAndView;
}
}
4.3.2、编写jsp
编写itemsList.jsp文件,存于/springmvcfirst/WebRoot/WEB-INF/jsp/items/itemsList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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>
<form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.price }</td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/item/editItem.action?
id=${item.id}">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
4.4、三层代码编写总结
4.4.1、dao层
1、逆向工程生成单表的po类及mapper
2、手动定义多表的po类和mapper(包括mapper.java和mapper.xml)
一般多表的po类继承自主表,次表以属性形式加载在po类中。在mapper.xml定义操作数据库的sql语句,在mapper.java中编写sql语句对应的抽象方法。
4.4.2、service层
1、编写service接口,对应于所调用的dao层的mapper.java
2、编写service接口的实现类,并在其中注入mapper代理对象
4.4.3、表现层
1、编写Controller(就是Handler),由于表现层handler要调用service接口,故需要在handler中注入service接口。
2、编写jsp
五、部署测试
Debug方式执行Service打开浏览器,输入相应的Handler的url即可。