SpringMVC与Mybatis整合---SpringMVC学习笔记(六)

SpringMVC整合Mybatis的系统架构:

这里写图片描述

整合思路

第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

第二步:整合service层
通过spring管理 service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。

第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。

需求

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

整合过程:

第一步:搭建工程结构

这里写图片描述
注意:lib中是springMVC和mybatis整合需要的jar

第二步:整合Dao层(mybatis和spring进行整合)

1.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="com.huihui.pojo"/>
    </typeAliases>

    <!-- 配置mapper
        由于使用spring和mybatis的整合包进行mapper扫描,所以这里就不需要配置了。
        但是必须遵循:mapper.xml和mapper.java文件同名并且在同一个目录下。
     -->
    <!-- <mappers></mappers> -->

</configuration>

2.spring的配置文件:applicationContext-dao.xml
配置:

  1. 数据源
  2. SqlSessionFactory
  3. 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文件中的内容 -->
    <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 -->
    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <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.huihui.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

</beans>

3.逆向工程生成pojo类和mapper(包括mapper.xml和mapper.java,但是只是包含对单表的增删改查)
这里写图片描述
然后将生成的文件拷贝至工程中。

4.手工定义商品查询mapper(包括mapper.xml和mapper.java)
针对综合查询mapper,一般情况会有关联查询,建议自定义mapper。不要使用逆向生成的mapper。

1.pojo类:
Items.java是有上面的逆向工程生成的商品信息的pojo类,一般不要改动,所以说如果对Items类的属性进行扩展最好单独创建一个继承Items的pojo类。

继承Items类的pojo类:

public class ItemsCustom extends Items {

    //商品信息的扩展属性

}

为了方便往表现层传数据而创建的pojo类:

package com.huihui.pojo;

/**
 * 商品信息的包装对象
 * @author 62347
 *
 */
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;
    }


}

2.mapper.xml映射文件:(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.huihui.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="com.huihui.pojo.ItemsQueryVo" resultType="com.huihui.pojo.ItemsQueryVo">
        select items.* from items
        <where>
            <include refid="query_items_where"></include>
        </where>
     </select>

</mapper>

3.mapper接口:

public interface ItemsMapperCustom {
    //商品查询列表
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}

第三步:整合service层

1.定义service接口
ItemsService接口:

public interface ItemsService {

    //商品查询列表
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;

}

ItemsServiceImpl实现类:

public class ItemsServiceImpl implements ItemsService {

    @Autowired
    private ItemsMapperCustom itemsMapperCustom;

    @Override
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
            throws Exception {
        //通过ItemsMapperCustom查询数据库
        return itemsMapperCustom.findItemsList(itemsQueryVo);
    }

}

注意:上面使用了@Autowired:
因为之前applicationContext-dao.xml文件中配置了mapper的扫描器

    <!-- 配置mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.ClassPathMapperScanner">
        <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
        <property name="basePackage" value="com.huihui.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

所以这里就可以直接注入了。

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

创建applicationContext-service.xml,文件中配置service。

        <!-- 商品管理的service -->
        <bean id="itemsService" class="com.huihui.service.impl.ItemsServiceImpl"></bean>

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

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

<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(* com.huihui.service.impl.*.*(..))"/>
        </aop:config>
</beans>

第四步:整合SpringMVC

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"
    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 ">

    <!-- 扫描controller注解,base-package指定要扫描的包。多个包中间使用半角逗号分隔 -->
    <context:component-scan base-package="com.huihui.controller" />

    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 配置视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- prefix表示jsp路径的前缀,suffix表示jsp路径的后缀 -->
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

2.配置前端控制器
在web.xml中配置前端控制器

 <!-- 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:springmvc.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- 
        url-pattren有很多中配置方式:
        第一种:*.action,表示访问以.action结尾由DispatcherServlet进行解析
        第二种:/,表示所有访问的地址都由springmvc的DispatcherServlet进行解析
        第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,仍然会由DispatcherServlet进行解析jsp,但是并不能根据这个jsp找到对应的handler,所以会报错
     -->
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

3.编写Controller(也就是Handler)

package com.huihui.controller;

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 com.huihui.pojo.ItemsCustom;
import com.huihui.service.ItemsService;

@Controller
public class ItemsController {

    @Autowired
    private ItemsService itemsService;

    // 商品查询列表
    // @RequestMapping实现对queryItmes方法和url进行映射,一个方法对应一个url。一般建议将url和方法名写成一样
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception {

        //调用service查找数据库,查询商品列表
        List<ItemsCustom> itemsList = itemsService.findItemsList(null);

        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        // 相当于request的setAttribute()方法,以后在jsp页面中可以通过itemsList取数据
        modelAndView.addObject("itemsList", itemsList);

        // 指定视图
        // modelAndView.setViewName("/jsp/items/itemsList.jsp");
        // 上面的路径,如果在视图解析器中配置了jsp路径的前缀和jsp路径的后缀,就可以修改为下面这样
        modelAndView.setViewName("items/itemsList");

        return modelAndView;
    }
}

4.编写前端jsp页面
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>

第五步:加载Spring容器

将mapper、service、controller加载到spring容器中。
这里写图片描述
建议使用通配符加载上边的配置文件。

在web.xml中,添加spring容器监听器,加载spring容器。

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

第六步:请求访问

这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值