2.springMVC+spring+Mybatis整合

前面已经说了,springMVC+spring+Mybatis的整合思路了,现在就照着这个思路来做一下:

  在开始之前先来看一下工程的目录结构:

  config这个目录底下放的都是配置文件:

    mybatis-config.xml是Mybatis的全局配置文件

    applicationContext.xml是spring的配置文件

    dispatch-servlet.xml是springMVC的配置文件

    另外两个是数据库的文件和日志文件

  首先是jar,对于jar我就不贴出来了(这里整合的都是3.x的)记得把该有的jar都添加进去就好了

  

  整合dao(spring和mybatis的整合过程):就是在applicationContext.xml中添加底下的bean

        配置数据源的文件路径

    配置数据源

        配置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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                        http://www.springframework.org/schema/tx 
                          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
                          http://www.springframework.org/schema/aop 
                          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
                          
              <!-- 配置数据源的文件的位置 -->
              <context:property-placeholder location="classpath:db.properties"/>
              <!-- 配置数据源  可以使用DriverManagerDataSource 或ComboPooledDataSource 后者比较强大:com.mchange.v2.c3p0.ComboPooledDataSource 需要c3p0的包  -->
              <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                  <property name="driverClassName" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
                <!-- 数据库连接池(需要数据源连接池的可以自己配置) -->
              </bean>
              
              <!-- 配置SqlSessionFactory -->
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <!-- 指定数据源 -->
                <property name="dataSource" ref="dataSource"></property>
                <!-- 指定Mybatis配置文件的路径 -->
                <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
            </bean>
            <!-- 配置mapper的扫描包 -->
            <!-- 去扫描bean的时候,有一个取名字的规则:bean的名字=原先类的类名小写,这个是为了做测试的时候看看spring和Mybatis有没有整合成功的时候需要使用到 -->
            <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <property name="basePackage" value="com.etc.dao"></property>
                <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
            </bean>
          
</beans>

    db.properties配置文件的配置信息

#数据源的配置信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/jc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

    log4j.properties的配置信息

log4j.rootLogger=DEBUG, stdout
log4j.appender.CONSOLE.Encoding=UTF-8
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d[%t]%-5p[%c]-%m%n
log4j.appender.syslog.encoding=UTF-8

    到这来spring和Mybatis就整合完成了,完成之后,建议大家建立一个测试类,测试一下spring和Mybatis是否整合成功,否则后期一旦出错,就要从头开始查,比较麻烦

    测试类代码如下:因为我们在spring的配置中是采用扫描包的方式进行mapper.xml文件是扫描,所以必须要遵循包扫描的几个规则这里重复一遍:   

      规则:1.mapper接口和mapper.xml映射文件的名称必须一致

                  2.mapper接口和mapper.xml映射文件必须在同一个目录

          

public class TestUser {
    @Test
    public void findAll() {
        //获取spring配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "classpath:spring/applicationContext.xml");
        //得到mapper.xml:bean的值就是你类名的小写,并且要求你dao接口和实现的xml名字必须一样
        UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
        List<User>list=userMapper.findAll();
        for (User user : list) {
            System.out.println(user);
        }    
    }
}

    这里的测试类只要你有查询出数据的东西,就说明你整合的spring和Mybatis没有问题,就可以继续往下面走了。

  整合service(让spring管理sevice的过程):这个也很简单就是添加配置文件就OK,但是这里有两种方式:第一种是注释的事务配置,第二种是非注解的事务配置

        事务的配置

        通知(哪一些事务需要提交,哪一些还不需要)

        Aop

  注解的配置(配置文件):

<!-- 4. 事务管理 : DataSourceTransactionManager -->
    <bean id="txManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 5. 使用声明式事务 -->
    <tx:annotation-driven transaction-manager="txManager" />

  service中注解的使用:(在方法上加上@Transactional

@Transactional//要在你的方法上加上这个注解

public void insertUser(User user) {

    userMapper.insertUser(user);
}

  非注解的配置:

<!-- 事物的配置 -->
            <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <!-- 数据源 -->
                <property name="dataSource" ref="dataSource"></property>
            </bean>
            <!-- 通知 -->
            <tx:advice transaction-manager="transactionManager" id="txAdvice">
                <!-- 传播行为:什么方法需要用到事物 -->
                <tx:attributes>
                    <!--<tx:method name="*" rollback-for="RunTimeException"/>-->
                    <tx:method name="save*" propagation="REQUIRED"/>
                    <tx:method name="delete*" propagation="REQUIRED"/>
                    <tx:method name="update*" propagation="REQUIRED"/>
                    <tx:method name="insert*" propagation="REQUIRED"/>
                    <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
                    <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
                </tx:attributes>
            </tx:advice>
            <!-- Aop 告诉spring哪里需要用到事物-->
            <aop:config>
                <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.etc.service.impl.*.*(..))"/>
            </aop:config>

  整合springmvc(不需要整合,只要丢配置文件就好了):把springMVC的配置文件放进去就行

        前置过滤器

        默认的注解支持

        视图解析器

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- 默认的注解映射支持 -->
    <mvc:annotation-driven/>
    <!-- 启用自动扫描 -->
    <context:component-scan base-package="com.etc.*"></context:component-scan>
    <!-- 配置ViewResolver -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

   在web.xml中加载spring的配置文件和指定springMVC的文件位置(默认是在WEB-INF底下的servlet名字-servlet.xml,现在被我们放到了config底下了)

   

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    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_2_5.xsd">

      <!-- spring 容器配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- spring 配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring/applicationContext.xml</param-value>
    </context-param>
  <!--前置过滤器的配置--> <servlet> <servlet-name>dispatch</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 默认的配置文件的地址:/WEB-INF/servlet的名字-servlet.xml <init-param>--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/dispatcher-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatch</servlet-name> <!-- 第一种:*.html,*.action 就是过滤以.xxx结尾的 第二种:/ 所有的地址都会进入这个进行解析,静态的资源,需要添加配置 第三种:/* 他就是变态,连jsp页面都进来,结果就是报错XXXXX别用 --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

  到此整合结束,下一篇会把增删改查的demo直接贴代码给大家

原文地址:https://www.cnblogs.com/huaixiaoz/p/5803198.html