springMVC教程初级(三)springmvc+Mybatis整合(重点 )

一、前言

1.1回顾SpringMVC

上一章讲解SpringMVC的一些详细分析,主要讲解了
非注解两种映射器:BeanNameUrlHandlerMapping、SimpleUrlHandlerMapping;两种适配HttpRequestHandlerAdapter、SimpleControllerHandlerAdapter
注解的映射器RequestMappingInfoHandlerMapping注解的适配器:AnnotationMethodHandlerAdapter
视图解析器ViewResolver
以及如何通过DispatcherServlet来一步步实现了MVC,返回页面组装数据的

1.2计划SpringMVC+Mybatis

之前讲过Mybatis与Spring整合(Mybatis的章节),这里我们讲一下SpringMVC与Mybatis整合
第一步:整合Dao,spring与mybatis整合
第二步:整合Service,Service可以调用Mapper
第三步:整合Controller,Controller可以调用Service

二、SpringMVC整合Mybatis

2.1 Jar包导入

<pre name="code" class="html"><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ycy.spring01</groupId>
  <artifactId>spring01</artifactId>
  <packaging>war</packaging>
  <version>1.0-spring01</version>
  <name>spring Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--数据库驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!--数据库链接-->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!--springMvc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.7</version>
    </dependency>
    <!--log4j官方推荐jar-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.3</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.3</version>
    </dependency>
    <!--log4j实现slf4j:因为Mybatis是用的slf4j-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>2.3</version>
    </dependency>
    <!--spring+Mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <!--servlet包-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>
    <!--标签库-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>spring01</finalName>
  </build>
</project>


2.2 配置整合开启

按照SpringMVC的制度一步步来

2.2.1 配置Dao1:applicationContext-dao.xml ---数据源、SqlsessionFactory、Mapper扫描

2.2.2 配置Dao2:SqlMapConfig.xml---mybatis的配置文件,配置别名、settingsmapper

2.2.3  配置Service1applicationContext-service.xml---配置service接口

2.2.4  配置Service2:applicationContext-transaction.xml--事务管理

2.2.5  配置Controller与MVC:sprintmvc.xml---springmvc的配置,配置处理器映射器、适配器、视图解析器

记住口诀:2Dao+2Service+1MVC=springMVC+mybatis

2.2.1配置Dao

1、我们将spring-dao与事务一起配置:构成applicationContext-dao.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-4.0.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.0.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">
    <!-- ========================================配置数据源========================================= -->
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:/config/db.properties"/>
    <!-- 数据库连接池 -->
    <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>
    <!-- ========================================针对myBatis的配置项============================== -->
    <!-- SqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置扫描包的路径 如果要扫描多个包,中间使用半角逗号分隔 -->
        <property name="basePackage" value="com.ycy.mapper"/>
        <!-- 使用sqlSessionFactoryBeanName -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
    <!-- ========================================事物配置========================================= -->
    <!-- 事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- aop -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
                     pointcut="execution(* com.ycy.service.impl.*.*(..))"/>
    </aop:config>
</beans>
2、依照订单为例子建立mapper与sqlconfig

sqlMapConfig.xml如下:

<pre name="code" class="html"><!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- =================================全局配置参数=============================== -->
    <settings>
        <!-- 延迟加载总开关 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 设置按需加载 -->
        <setting name="aggressiveLazyLoading" value="false" />
        <!-- 二级缓存总开关 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <!--===============================加载mapper====================================-->
    <mappers>
        <!--1:通过resource路径导入xml映射(idea必须在resource文件下面)-->
        <mapper  resource="mapper/ItemsMapper.xml"/>
        <!--3:通过批量导入package,自动扫描包下面mapper接口 注意:此时class文件必须与想xml文件在一个目录下,同名-->
        <!--<package name="com.ycy.mybatis.dao"/>-->
    </mappers>
</configuration>


ItemsMapper.xml如下:

<pre name="code" class="html"><?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="com.ycy.mapper.ItemsMapper">

<select id="getItemsById" parameterType="com.ycy.dto.parameter.ItemsCustom"
            resultType="com.ycy.dto.result.ItemsCustomResult">
  SELECT  * from items WHERE  id=#{id}
</select>

    <select id="findtemsList" parameterType="com.ycy.dto.parameter.ItemsCustom"
            resultType="com.ycy.dto.result.ItemsCustomResult">
    SELECT  * from items
  </select>
</mapper>







3、配置mapper.java

<pre name="code" class="html">package com.ycy.mapper;

import com.ycy.dto.parameter.ItemsCustom;
import com.ycy.dto.result.ItemsCustomResult;

import java.util.List;

/**
 * Created by Administrator on 2015/9/22 0022.
 */
public interface ItemsMapper {
    public ItemsCustomResult getItemsById(ItemsCustom itemsCustom);

    public List<ItemsCustomResult> findtemsList(ItemsCustom itemsCustom);


}


2.2.1配置Service

1、applicationContext-service.xml配置文件
<pre name="code" class="html"><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-4.0.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">

    <!-- 扫描service 包配置 -->
	<context:component-scan base-package="com.ycy.service"/>

</beans>




2、service的java文件
ItemsService:如下
<pre name="code" class="html">package com.ycy.service;

import com.ycy.dto.parameter.ItemsCustom;
import com.ycy.dto.result.ItemsCustomResult;

import java.util.List;

/**
 * Created by Administrator on 2015/9/22 0022.
 */
public interface ItemsService {
    public ItemsCustomResult getItemsById(Integer id, ItemsCustom itemsCustom) throws Exception;

    public List<ItemsCustomResult> findtemsList(ItemsCustom itemsCustom)throws Exception;;
}



ItemsServiceImpl如下:
<pre name="code" class="html">package com.ycy.service.impl;

import com.ycy.dto.parameter.ItemsCustom;
import com.ycy.dto.result.ItemsCustomResult;
import com.ycy.mapper.ItemsMapper;
import com.ycy.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2015/9/22 0022.
 */
public class ItemsServiceImpl implements ItemsService {
    @Autowired
    private ItemsMapper itemsMapper;

    public ItemsCustomResult getItemsById(Integer id,ItemsCustom itemsCustom) throws  Exception{
        if(id!=null){
            return itemsMapper.getItemsById(itemsCustom);
        }else{
            throw new Exception("query id is null");
        }

    }

    public List<ItemsCustomResult> findtemsList(ItemsCustom itemsCustom) throws Exception {
        return itemsMapper.findtemsList(itemsCustom);
    }


}



2.2.3配置Controller

1、首先我们需要把service、dao加入web环境,再加上之前配置的Dispatcher,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"
         metadata-complete="false">
    <!-- 配置spring容器监听器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 设置servlet编码开始 -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>
    <!-- 设置servlet编码结束 -->
    <display-name>Archetype Created Web Application</display-name>
    <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:spring/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</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><span style="color:#000099;">
</span>

2、SpringMVC文件编写
<pre name="code" class="html"><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-4.0.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">
    <!--1、=========================dispatcher已经在web.xml里面配置=============================-->
    <!-- 使用spring组件扫描 -->
    <context:component-scan base-package="com.ycy.controller"/>

    <!-- 2、3 通过annotation-driven可以替代下边的处理器映射器和适配器 -->
    <!-- 	<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>-->


    <!--2、=======================使用注解RequestMappingInfoHandlerMapping映射器==================== -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

    <!--3、=============================处理器适配器HandlerAdapter================================-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

    <!--4、============================视图解析器ViewResolver======================================-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/pages/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--5、视图view与hanlder需要自己实现-->
</beans>





3、编写Controller的java文件
ItemController如下:
<pre name="code" class="html">package com.ycy.controller;


import com.ycy.dto.parameter.ItemsCustom;
import com.ycy.dto.result.ItemsCustomResult;
import com.ycy.model.Items;
import com.ycy.service.ItemsService;
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 java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2015/9/17 0017.
 */
@Controller
public class ItemController {
    @Autowired
    private ItemsService itemsService;
    @RequestMapping("/queryItems")
    public ModelAndView queryItems(javax.servlet.http.HttpServletRequest httpServletRequest,
                                      javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        ItemsCustom itemsCustom=new ItemsCustom();
        itemsCustom.setId(1);
        //商品列表
        List<ItemsCustomResult> itemsList = itemsService.findtemsList(null);

        //创建modelAndView准备填充数据、设置视图
        ModelAndView modelAndView = new ModelAndView();
        //填充数据
        modelAndView.addObject("itemsList", itemsList);
        //视图
        modelAndView.setViewName("order/itemsList");

        return modelAndView;
    }
}


2.2.3 编写页面

itemsList.jsp如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"  %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询商品列表</title>
</head>
<body> 
<form action="${pageContext.request.contextPath }/items/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:33
<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 }/items/editItems.action?id=${item.id}">修改</a></td>

		</tr>

	</c:forEach>
</table>
</form>
</body>

</html>


2.2.4 配置完成结构如下:

springMVC教程初级(三)springmvc+Mybatis整合(重点 )



三、总结

1、整合Jar:log4j的包导入log4j实现slf4j:因为Mybatis是用的slf4j
          aspectjweaver包的导入,它的作用起到事务管理作用,相信在不久的将来会融合到springMVC中,至少目前我们用这种方法除开springMvc包还需          要两个包才能构成MVC完整,那就是spring.jdbc 与aspectjweaver,一般用他们管理事务。

2、整合顺序:对于很多新手,最好还是按照我的dao-service-Controller来整合,一步步来。整合完,再根据我提供的demo一步步检查对比。

3、忠告:项目中用到的sql、数据库 与po等完全不用放心上,因为你如果需要参照项目做,可以去git上下载下来我spring01项目,下载下来就是一个maven项目。之所以一步步将整合,不想其他的直接每个贴出来,就是想让学习的人一步步了解。一步步学习懂得,而不是复读机,没得意思····


上一篇:《树莓派开发实战(第2版)》——1.13 关闭树莓派


下一篇:【超全整理】J2EE集成开发环境MyEclipse使用心得汇总