SpringMVC整合mybatis

使用Spring+SpringMVC+Mybatis实现SSM开发方式

1、创建一个web工程

2、导入所有需要使用到的jar包

 1.Mybatis需要的所有jar包。

 2.Spring的所有jar包。

 3.数据库驱动包。

 4.Mybatis和Spring的整合包。

 5.log4j的日志包。

 6.dbcp数据库连接池的jar包。

 7.jstl的jar包。

3、整合思路

 1.整合dao层
  mybatis和spring进行整合,通过spring来管理mapper接口。使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
 2.整合service层
  通过sprin来管理service接口。使用配置方式将service接口配置到spring的配置文件中。实现事务的控制。
 3.整合springmvc
  因为springmvc是spring的一个模块,不用进行中间层整合。

4、创建mybatis的全局配置文件mybatis.xml

 由于使用了Spring来管理mybatis,所有在mybatis的全局文件中只需要配置pojo的别名和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>

    <!--配置批量设置mapper别名-->
    <typeAliases>
        <package name="com.jack.po"/>
    </typeAliases>
</configuration>

5、创建Spring的配置文件

 在Spring的配置文件中要配置数据源,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 ">
<!--加载数据库的配置文件-->
<context:property-placeholder location="classpath:config/db.properties"/>

    <!--配置数据源,使用dbcp连接池-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${mysql.jdbc.driver}" />
        <property name="url" value="${mysql.jdbc.url}"/>
        <property name="username" value="${mysql.jdbc.username}"/>
        <property name="password" value="${mysql.jdbc.password}"/>
        <property name="maxActive" value="30"/>
        <property name="maxIdle" value="5"/>
    </bean>

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

    <!--配置mapper扫描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
        <!--注入mapper文件所在的包-->
        <property name="basePackage" value="com.jack.mapper"/>
        <!---注入SqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSesionFactory"/>
    </bean>
</beans>

6、编写POJO

 pojo中的属性名称要和数据库中列名称保持一致。

public class Items {
    private Integer id;

    private String name;

    private Float price;

    private String pic;

    private Date createtime;

    private String detail;
    //setter and getter
}

7、编写ItemMapper.xml文件

 第六步和第七步可以使用mybatis的逆向工程进行代码生成,具体方法见 mybatis逆向工程

<?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.jack.mapper.ItemsMapper">
    <!--查询全部商品-->
    <select id="queryItesm" resultType="itemsExtend" >
        SELECT * FROM items
    </select>
</mapper>

8、编写ItemMapper接口文件

public interface ItemsMapper {

    public List<ItemsExtend> queryItesm() throws Exception;

}

9、编写service接口文件

public interface ItemsService {
    public List<ItemsExtend> queryItesm() throws Exception;

}

10、编写service接口的实现

public class ItemsServiceImpl implements ItemsService {

    //注入mapper
    @Autowired
    ItemsMapper itemsMapper;

    @Override
    public List<ItemsExtend> queryItesm() throws Exception {
        return itemsMapper.queryItesm();
    }

}

11、编写Spring的配置文件来配置service

<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 ">
    <!-- 商品管理的service -->
    <bean id="itemsService" class="com.jack.service.impl.ItemsServiceImpl"/>
</beans>

12、编写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"/>
    </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.jack.service.impl.*.*(..))"/>
    </aop:config>

</beans>

13、编写SpringMVC的配置文件

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


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

    <!--使用组件扫描的方式配置Handler-->
    <!-- 对于注解的Handler可以单个配置 实际开发中建议使用组件扫描-->
    <!-- <bean class="cn.itcast.ssm.controller.ItemsController3" /> -->
    <!-- 可以扫描controller、service、...
    这里让扫描controller,指定controller的包
     -->
    <context:component-scan base-package="com.jack.controller" ></context:component-scan>

    <!--配置视图解析器,解析jsp页面,默认使用jstl标签-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <!--配置视图解析器的前缀-->
        <property name="prefix" value="/page/"/>
        <!--配置视图解析器的后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

14、编写handler

@Controller
public class controller {

    //注入service接口
    @Autowired
    ItemsService itemsService;
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception{
        List<ItemsExtend> itemsExtendList =itemsService.queryItesm();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemsExtendList",itemsExtendList);
        modelAndView.setViewName("itemlist");
        return modelAndView;
    }
}

15、编写view

<%@ 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>
         <title>商品展示</title>
    </head>
    <body>
        <form action="${pageContext.request.contextPath}/queryItems.action" >
            <table width="100%" border= 1>
                <tr>
                    <td><input type="submit" value="查询"></td>
                </tr>
                <tr>
                    <td>商品id</td>
                    <td>商品名称</td>
                    <td>商品价格</td>
                </tr>
                <c:forEach items="${itemsExtendList}" var="items">
               <tr>
                    <td>${items.id}</td>
                    <td>${items.name}</td>
                    <td>${items.price}</td>
               </tr>
                </c:forEach>
            </table>
        </form>
    </body>
</html>

16、编写web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--加载Spring容器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/applicationContext-*.xml</param-value>
    </context-param>
    <!--配置监听器,启动就加载Spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!--
                配置SpringMVC加载的配置文件位置
                如果不配置默认加载WEB-INF目录下的名称为:Servlet名称-servlet.xml的文件
            -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/springmvc.xml</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
            url-parrern的配置有三种:
            1、*.action 访问已action结尾的URL是由DispatcherServlet进行解析
            2、/  所有的访问URL都由DispatcherServlet进行处理,对于静态资源要配置不让其解析,
                    这种方式可以实现RESTFul风格。
            3、/* 这种配置方式经测试不正确
        -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

17、数据库的配置文件

mysql.jdbc.driver = com.mysql.jdbc.Driver
mysql.jdbc.url = jdbc:mysql:///springmvc
mysql.jdbc.username= root
mysql.jdbc.password = root

18、log4j的配置文件

# Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
log4j.rootLogger=DEBUG, stdout
# 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
posted @ 2017-08-14 14:15  一条路上的咸鱼  阅读(320)  评论(0编辑  收藏  举报