springmvc和mybatis整合—商品查询

作者: 小小蒜头 | 来源:发表于2017-12-11 15:28 被阅读107次

    1. 需求

    使用springmvc和mybatis完成商品列表查询

    2. 整合思路

    springmvc+mybaits的系统架构:

    系统架构
    第一步:整合dao层
        mybatis和spring整合,通过spring管理mapper接口。
        使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
    
    第二步:整合service层
        通过spring管理 service接口。
        使用配置方式将service接口配置在spring配置文件中。
        实现事务控制。
    
    第三步:整合springmvc
        由于springmvc是spring的模块,不需要整合。
    

    3. 准备环境

    数据库环境:mysql5.5

    数据库表

    java环境:
    jdk1.8
    IDEA

    所需要的jar包:
    数据库驱动包:mysql5.1
    mybatis的jar包
    mybatis和spring整合包
    log4j包
    dbcp数据库连接池包
    spring3.2所有jar包
    jstl包

    <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.eurasia</groupId>
        <artifactId>SpringMVC_mybatis</artifactId>
        <packaging>war</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>SpringMVC_mybatis Maven Webapp</name>
        <url>http://maven.apache.org</url>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <!-- spring版本号 -->
            <spring.version>4.0.9.RELEASE</spring.version>
            <!-- mybatis版本号 -->
            <mybatis.version>3.3.0</mybatis.version>
            <!-- mysql驱动版本号 -->
            <mysql-driver.version>5.1.18</mysql-driver.version>
            <!-- log4j日志包版本号 -->
            <slf4j.version>1.7.18</slf4j.version>
            <log4j.version>1.2.17</log4j.version>
        </properties>
        <dependencies>
            <!-- 添加jstl依赖 -->
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-api</artifactId>
                <version>7.0</version>
            </dependency>
            <!-- 添加junit4依赖 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <!-- 指定范围,在测试时才会加载 -->
                <scope>test</scope>
            </dependency>
    
            <!-- 添加spring核心依赖 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-oxm</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.6</version>
            </dependency>
            <!-- 添加mybatis依赖 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!-- 添加mybatis/spring整合包依赖 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.2.2</version>
            </dependency>
            <!-- 添加mysql驱动依赖 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-driver.version}</version>
            </dependency>
    
            <!-- 添加数据库连接池依赖 -->
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>1.2.2</version>
            </dependency>
            <!-- 添加日志相关jar包 -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
        </dependencies>
    
        <build>
            <finalName>SpringMVC_mybatis</finalName>
        </build>
    </project>
    

    4. 整合dao

    4.1 sqlMapConfig.xml

    mybatis自己的配置文件。

    <?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>
    
        <!--配置别名-->
        <typeAliases>
            <!--批量扫描别名-->
            <package name="com.eurasia.pojo"/>
        </typeAliases>
        <!--配置mapper
        由于使用Spring和mybatis的整合包进行mapper扫描,这里不需要配置
        必须遵循mapper.xml和mapper.java文件同名且在一个目录
        -->
    </configuration>
    

    4.2 applicationContext-dao.xml

    配置:数据源、SqlSessionFactory、mapper扫描器

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           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.2.xsd 
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-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="30"/>
            <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扫描器 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
            <property name="basePackage" value="com.eurasia.mapper"></property>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>
    </beans>
    

    4.3 逆向工程生成po类及mapper(单表增删改查)

    效果

    4.4 手动定义商品查询mapper

    针对综合查询mapper,一般情况会有关联查询,建议自定义mapper。

    4.4.1 ItemsMapperCustom.xml

    sql语句: SELECT * FROM items WHERE items.name LIKE '%笔记本%'

    <?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.eurasia.mapper.ItemsMapperCustom">
        <!--定义商品查询的sql片段,就是商品查询条件-->
        <!--使用动态sql,通过if判断,满足条件进行sql拼接
           商品查询条件通过ItemsQueryVo包装对象中itemsCustom属性传递-->
        <sql id="query_items_where">
            <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="com.eurasia.pojo.ItemsQueryVo" resultType="com.eurasia.pojo.ItemsCustom">
            SELECT items.* FROM items
            <where>
                <include refid="query_items_where"/>
            </where>
        </select>
    </mapper>
    

    4.4.2 ItemsMapperCustom.java

    package com.eurasia.mapper;
    
    
    import com.eurasia.pojo.ItemsCustom;
    import com.eurasia.pojo.ItemsQueryVo;
    
    import java.util.List;
    
    public interface ItemsMapperCustom {
        //商品查询列表
        public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
    }
    

    5 整合service

    让spring管理service接口。

    5.1 定义service接口

    package com.eurasia.service;
    
    import com.eurasia.pojo.ItemsCustom;
    import com.eurasia.pojo.ItemsQueryVo;
    
    import java.util.List;
    
    public interface ItemsService {
        //商品查询列表
        public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
    }
    
    
    package com.eurasia.service.impl;
    
    import com.eurasia.mapper.ItemsMapperCustom;
    import com.eurasia.pojo.ItemsCustom;
    import com.eurasia.pojo.ItemsQueryVo;
    import com.eurasia.service.ItemsService;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import java.util.List;
    
    public class ItemsServiceImpl implements ItemsService {
        @Autowired
        private ItemsMapperCustom itemsMapperCustom;
    
        public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
            //通过ItemsMapperCustom查询数据库
            return itemsMapperCustom.findItemsList(itemsQueryVo);
        }
    }
    

    5.2 在spring容器配置service(applicationContext-service.xml)

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
            ">
        <!-- 商品管理的service -->
        <bean id="itemsService" class="com.eurasia.service.impl.ItemsServiceImpl"/>
    </beans>
    

    5.3 事务控制(applicationContext-transaction.xml)

    在applicationContext-transaction.xml中使用spring声明式事务控制方法。

    <!--suppress ALL -->
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           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/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"/>
        </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(* com.eurasia.service.impl.*.*(..))"/>
        </aop:config>
    </beans>
    

    6. 整合SpringMVC

    6.1 springmvc.xml

    创建springmvc.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"
           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">
    
        <!-- 可以扫描controller、service、...
        这里让扫描controller,指定controller的包
         -->
        <context:component-scan base-package="com.eurasia.controller"></context:component-scan>
    
        <!-- 使用 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>
    

    6.2 配置前端控制器

    在web.xml文件里作如下配置

    <!DOCTYPE web-app PUBLIC
            "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
            "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
        <display-name>Archetype Created Web Application</display-name>
        <!--加载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>
    
        <!--SpringMVC前端控制器-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--contextConfigLocation配置SpringMVC加载的配置文件(配置处理器映射器、适配器等等)
            如果不配置contextConfigLocation,默认加载/WEB-INF/servlet名称-servlet.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>
            <url-pattern>*.action</url-pattern>
        </servlet-mapping>
    </web-app>
    

    6.3 编写Controller(就是Handler)

    package com.eurasia.controller;
    
    import com.eurasia.pojo.ItemsCustom;
    import com.eurasia.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.List;
    
    /**
     * Created by yvettee on 2017/11/30.
     */
    @Controller
    public class ItemsController{
    
        @Autowired
        private ItemsService itemsService;
    
        @RequestMapping("/queryItems")
        public ModelAndView queryItems() throws Exception {
    
            //调用service查找数据库,查询商品列表,这里使用静态数据模拟
            List<ItemsCustom> list = itemsService.findItemsList(null);
    
    
            //返回ModelAndView
            ModelAndView modelAndView = new ModelAndView();
            //相当于request.setAttribute
            modelAndView.addObject("itemslist", list);
    
            //指定视图
            modelAndView.setViewName("/items/itemsList");
            return modelAndView;
        }
    }
    

    6.4 编写jsp

    itemsList.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <html>
    <head>
        <title>商品列表</title>
    </head>
    <body>
    <form action="/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="/item/editItem.action?id=${item.id}">修改</a></td>
                </tr>
            </c:forEach>
        </table>
    </form>
    </body>
    </html>
    

    7. 加载spring容器

    将mapper、service、controller加载到spring容器中。

    1.png

    建议使用通配符加载上边的配置文件。

    在web.xml中,添加spring容器监听器,加载spring容器。前面已给出。

    <!--加载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>
    

    下篇:springmvc和mybatis整合—商品修改功能
    源代码:https://github.com/yvettee36/SpringMVC_mybatis

    相关文章

      网友评论

        本文标题:springmvc和mybatis整合—商品查询

        本文链接:https://www.haomeiwen.com/subject/xljzbxtx.html