springmvc和mybaits整合案例

springmvc和mybaits整合

整合思路

一、整合dao层

mybatis与spring的整合,最终目的是通过spring管理mapper接口.

使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

二、整合Service层

通过spring管理Service接口

使用配置的方式将Service接口配置在spring配置文件中

这一步还需要实现事务控制

三、整合springmvc

由于springmvc是spring的子模块,所有 不需要整合。

环境准备

相关工具版本:

jdk::1.8.0_102

mysql:5.6

开发工具:MyEclipse 14

服务器:apache-tomcat-7.0.42

spring版本:spring-framework-4.2.1.RELEASE-dist

mybatis版本:mybatis-3.4.4

所需jar包:

数据库驱动jar包——数据库连接驱动

mybatis的jar包——mybatis-all

mybatis与spring整合包——mybatis-spring-1.3.1.jar

log4j包——log4j-1.2.17.jar

commons-logging-1.1.1.jar——日志jar

数据库连接池(c3p0)jar——c3p0-0.9.2.1

mchange-commons-java-0.2.3.4.jar——c3p0搭配jar

spring所有jar——spring-all-jar

jstl标签库——jstl的jar

org.aspectj.weaver-1.6.8.RELEASE.jar

org.aopalliance-1.0.0.jar


构建工程

创相关的文件夹

工程结构

这里写图片描述

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/MyBatis?useUnicode=true&characterEncoding=UTF8
jdbc.username=root
jdbc.password=123456


log4j.properties

#Global logging configuration

log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n


整合dao

创建相关配置文件

SqlMapConfig.xml

在config文件下创建一个名为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>

        <!-- 批量定义别名
            指定包名,MyBatis会自动扫描包内类,自动定义别名,别名就是类名,首字母不区分大小写
         -->
        <package name="com.ld.ssm.po"/>
    </typeAliases>
  <!-- 配置mapper
    这个案例使用spring和mybatis的整合包进行mapper扫描,这里不需要配置
    不过必须遵循一定规则:
        mapper.xml与mapper.java同名且在同一个目录
   -->
 <!--  <mappers>
    <package name="com.hl.ld.mapper.UserMapper"/>
  </mappers> -->
</configuration>


applicationContext-dao.xml


config文件中创建spring文件夹,在spring文件夹创建applicationContext-dao.xml,这个配置文件中需要配置数据源、SqlSessionFactory以及mapper扫描器。

<?xml version="1.0" encoding="UTF-8"?>
<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"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
        <!-- 加载数据库配置信息 -->
        <context:property-placeholder location="classpath:db.properties"/>
        <!-- 数据源配置 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name= "driverClass" value="${jdbc.driver}"></property>
            <property name="jdbcUrl" value="${jdbc.url}"></property>
            <property name="user" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>


        <!-- SqlSessionFactory配置 
        -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 加载mybatis的配置文件 -->
            <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
            <!-- 数据源 -->
            <property name="dataSource" ref="dataSource"></property>
        </bean>


        <!-- 自动扫描mapper接口 
            也需要遵循mapper开发规范
            sqlSessionFactoryBeanName
        -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 指定扫描的包名 
                扫描多个包用半角逗号隔开
                获取mapper时是mapper接口名的首字母小写
            -->
            <property name="basePackage" value="com.ld.ssm.mapper"/>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>

</beans>


逆向工程生成文件

通过逆向工程生成mapper、mapper.xml、po类等文件

逆向工程操作请参考——mybatis逆向工程操作

将逆向工程得到的文件分别拷贝到相应目录下,结果如下

这里写图片描述

自定义商品查询mapper和相应映射文件


为了提高系统的扩展性,可以对原生po进行扩展,然后对使用包装对象对po类进行包装

扩展类ItemsCustomer .java

package com.ld.ssm.po;
/**
 * 商品信息的扩展类
 * @author 浪丶荡
 *
 */
public class ItemsCustomer extends Items{

    //添加扩展属性

}


包装类:ItemsQuerVo.java

package com.ld.ssm.po;
/**
 *  商品信息的包装类
 * @author 浪丶荡
 *
 */
public class ItemsQuerVo{

    private Items items;

    private ItemsCustomer itemsCustomer;

    public ItemsCustomer getItemsCustomer() {
        return itemsCustomer;
    }

    public void setItemsCustomer(ItemsCustomer itemsCustomer) {
        this.itemsCustomer = itemsCustomer;
    }

    public Items getItems() {
        return items;
    }

    public void setItems(Items items) {
        this.items = items;
    }
}


ItemsMapperCustomer.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="com.ld.ssm.mapper.ItemsMapperCustomer">
 <!-- 定义商品查询的sql片段  内容就是商品查询条件-->
 <sql id="query_items_where">
    <!-- 动态参数 通过if判断,满足条件进行sql拼接-->
    <!-- 这里的查询条件是通过包装类ItemsQuerVo中的itemsCustomer属性进行传递-->
    <if test="itemsCustomer!=null">
        <if test="itemsCustomer.name!=null and itemsCustomer!=''">
            items.name LIKE '%${itemsCustomer.name}%'
        </if>
    </if>
    items.name LIKE '%旺%'
 </sql>
 <!-- 商品列表查询
    parameterType:传入参数,建议使用包装对象
    resultType:建议使用扩展对象
  -->
 <select id="findItemsList" parameterType="com.ld.ssm.po.ItemsQuerVo"
            resultType="com.ld.ssm.po.ItemsCustomer">
    SELECT * FROM items
    <where>
        <include refid="query_items_where"></include>
    </where>

 </select>
</mapper>


ItemsMapperCustom.java

package com.ld.ssm.mapper;

import java.util.List;

import com.ld.ssm.po.ItemsCustomer;
import com.ld.ssm.po.ItemsQuerVo;


public interface ItemsMapperCustomer {
    //查询商品信息
    public List<ItemsCustomer> findItemsList(ItemsQuerVo itemsQuerVo)throws Exception;
}


整合Service层

定义接口

package com.ld.ssm.service;

import java.util.List;

import com.ld.ssm.po.ItemsCustomer;
import com.ld.ssm.po.ItemsQuerVo;

/**
 *  商品管理Service
 * @author 浪丶荡
 *
 */
public interface ItemsService {

    //商品查询列表
    public List<ItemsCustomer> findItemsList(ItemsQuerVo itemsQuerVo)throws Exception;
}


接口实现

package com.ld.ssm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.ld.ssm.mapper.ItemsMapperCustomer;
import com.ld.ssm.po.ItemsCustomer;
import com.ld.ssm.po.ItemsQuerVo;
import com.ld.ssm.service.ItemsService;

public class ItemsServiceImpl implements ItemsService {

    //注入itemsMapperCustomer
    @Autowired
    private ItemsMapperCustomer itemsMapperCustomer;
    @Override
    public List<ItemsCustomer> findItemsList(ItemsQuerVo itemsQuerVo)
            throws Exception {
        return itemsMapperCustomer.findItemsList(itemsQuerVo);
    }

}


创建applicationContext-service.xml

配置Service

<?xml version="1.0" encoding="UTF-8"?>
<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"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
       <bean id="itemsService" class="'com.ld.ssm.service.impl.ItemsServiceImpl"></bean>

</beans>


实现事务控制

创建applicationContext-transaction.xml

使用spring的声明式事务控制方法进行配置

<?xml version="1.0" encoding="UTF-8"?>
<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"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 事务管理器
        对于mybatis操作数据库事务控制,spring使用jdbc的事务控制
     -->
     <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="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="insert*" 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.ld.ssm.service.impl.*.*(..))"/>
     </aop:config>     
</beans>


整合springmvc

创建springmvc.xml文件

springmvc.xml文件中配置处理器映射器、处理器适配器、视图解析器

<?xml version="1.0" encoding="UTF-8"?>
<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"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
        <!-- mvc注解驱动
            代替处理器映射器、处理器适配器的配置
         -->
        <mvc:annotation-driven>


        </mvc:annotation-driven>
         <!-- 对于注解的Handler可以单个配置
              实际开发中建议使用组件扫描
          -->
         <context:component-scan base-package="com.ld.springmvc.controller"/>
        <!-- 视图解析器 
            配置解析jsp的视图解析器,默认使用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>


配置前端控制器

在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">
    <!-- springmvc前端控制器 -->
  <servlet>
    <servlet-name>beautiful</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置springmvc加载的配置文件(配置处理器映射器、适配器等) -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
  </servlet>

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

</web-app>


编写处理器(Controller即Handler)

注解方式开发Controller

package com.ld.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 com.ld.ssm.po.ItemsCustomer;
import com.ld.ssm.service.ItemsService;

/**
 *  商品的Controller
 * @author 浪丶荡
 *
 */
@Controller         //标识它是一个控制器
public class ItemsController {

    @Autowired
    private ItemsService itemsService;

    //商品查询
    @RequestMapping("/findItemsList.action")//建议将url与方法名一致。实现的是方法findItemsList与url进行映射
    public ModelAndView findItemsList()throws Exception{

        List<ItemsCustomer> itemsList = itemsService.findItemsList(null);
        ModelAndView modelAndView = new ModelAndView();
        //类似于request的setAttribute
        modelAndView.addObject("itemsList", itemsList);
        //指定视图

        modelAndView.setViewName("/items/itemsList");
        return modelAndView;
    }
    //商品修改
    //商品删除
}


编写前端页面

位置:

这里写图片描述

<%@ page language="java" import="java.util.*"  pageEncoding="UTF-8"%>
<%
response.setContentType("text/html;charset = GB2312");
request.setCharacterEncoding("gb2312");
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>查询商品列表</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </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.contentType }/item/editItem.action?id=${item.id}">修改</a></td>
            </tr>
            </c:forEach>
        </table>
    </form>
  </body>
</html>


加载spring容器

加载下列文件

这里写图片描述

添加spring容器监听器

在web.xml中最上边,添加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>

调试:访问路径

http://127.0.0.1/springmvc_mybatis/findItemsList.action


结果

这里写图片描述

终于还是出来了!

需要源码的加QQ群:511906138联系管理员

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值