springmvc(三)&与mybatis整合开发

8springmvc和mybatis整合

8.1需求

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

8.2整合的思路

    spring将各层进行整合
    通过spring管理持久层的mapper(相当于dao接口)
    通过spring管理业务层service service中可以调用mapper接口
    通过spring管理表现层Hanlder,handler中可以调用service接口
    spring进行事务控制
    mapper service Handler都是Javabean
    表现层
    springmvc

    业务层
    spring service接口        

    持久层
    mybatis

    数据库
    mysql
springmvc+mybatis的系统架构
第一步:整合dao持久层
    mybatis和spring整合,通过spring管理,mapper接口
    使用mapper的扫描器给自动扫描mapper接口在spring中进行注册

第二步:整合service层
    通过spring管理service接口
    使用配置方式将service接口配置在spring文件中
    实现事务控制
第三步“:整合springmvc
    由于springmvc是spring的模块,不需要整合

8.3环境

    java环境
    jdk
    srping3.2
    所需要的jar包
    数据库的驱动包 mysql5.1
    mybatis的jar包
    mybatis和是sping整合包
    log4j包
    dbcp数据库连接池
    spring3.2的所有jar包
    jstl包 

8.4整的dao

8.4.1SQLMapConfig.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文件同名且在一个目录 
                 -->

                <!-- <mappers>

                </mappers> -->
            </configuration>

8.4.2applicationContext-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="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="cn.itcast.ssm.mapper"></property>
                    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
                </bean>
            </beans>

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

8.4.4手动定义商品查询mapper

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

8.4.1ItemMapperCistom.xml

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

8.4.2ItemsMapperCustom.java

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

8.5整合service

8.5.1定义service接口

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

public class ItemsServiceImpl implements ItemsService{

    @Autowired
    private ItemsMapperCustom itemsMapperCustom;


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

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

创建applicationContext-service.xml,文件中配置service
        <!--商品管理的service-->
        <bean id="itemsService" class="cn.ssm.service.impl.ItemsServiceImpl"/>

8.5.3事务控制(applocationContext-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"/>
</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>

8.6整合springmvc

    创建springmvc.xml文件。配置处理器映射器 适配器 视图解析器

8.6.1springmvc.xml

<!-- 可以扫描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 conversion-service="conversionService"
    validator="validator"></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>

8.6.2配置前端控制器

 <!-- springmvc前端控制器 -->
    <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>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

8.6.3编写controller(或是handler)

// 商品查询
    @RequestMapping("/queryItems")
    public ModelAndView queryItems(HttpServletRequest request,
            ItemsQueryVo itemsQueryVo) throws Exception {
        // 测试forward后request是否可以共享

        System.out.println(request.getParameter("id"));

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

        // 返回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;

    }

8.6.4编写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>
<script type="text/javascript">
function deleteItems(){
    //提交form
    document.itemsForm.action="${pageContext.request.contextPath }/items/deleteItems.action";
    document.itemsForm.submit();
}
function queryItems(){
    //提交form
    document.itemsForm.action="${pageContext.request.contextPath }/items/queryItems.action";
    document.itemsForm.submit();
}
</script>
</head>
<body> 
当前用户:${username },
<c:if test="${username!=null }">
 <a href="${pageContext.request.contextPath }/logout.action">退出</a>
</c:if>
<form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItems.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>
商品名称:<input name="itemsCustom.name" />
商品类型:
<select name="itemtype">
    <c:forEach items="${itemtypes }" var="itemtype">
        <option value="${itemtype.key }">${itemtype.value }</option>      
    </c:forEach>
</select>

</td>
<td><input type="button" value="查询" onclick="queryItems()"/>
<input type="button" value="批量删除" onclick="deleteItems()"/>
</td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
    <td>选择</td>
    <td>商品名称</td>
    <td>商品价格</td>
    <td>生产日期</td>
    <td>商品描述</td>
    <td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>    
    <td><input type="checkbox" name="items_id" value="${item.id}"/></td>
    <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>

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



















猜你喜欢

转载自blog.csdn.net/qq_39128354/article/details/81428422