Mybatis和Spring整合

参考:http://www.mybatis.org/spring/zh/project-info.html

要理解整合过程,重点要理解配置文件,这里主要讲一下spring的配置文件applicationContext.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: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-4.0.xsd 
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-4.0.xsd 
               http://www.springframework.org/schema/tx
               http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
               http://www.springframework.org/schema/aop
               http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <import resource="classpath:datasource-context.xml"/>

    <!-- Activates scanning of @Autowired -->
    <context:annotation-config />

    <!--spring component scan -->
    <context:component-scan base-package="com.mybatis" />

    <!-- 使用annotation定义事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!--Configuration Repository -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>

</beans>

datasource-context.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: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-4.0.xsd 
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-4.0.xsd 
               http://www.springframework.org/schema/tx
               http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
               http://www.springframework.org/schema/aop
               http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
               ">
    <!--Default Data Source Initialize -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName">
            <value>${jdbc.driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc.url}</value>
        </property>
        <property name="username">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
        <property name="validationQuery">
            <value>${jdbc.validQuery}</value>
        </property>
        <property name="testOnBorrow">
            <value>true</value>
        </property>
        <property name="maxTotal">
            <value>${jdbc.maxTotal:5}</value>
        </property>
        <property name="maxIdle">
            <value>${jdbc.maxIdle:2}</value>
        </property>
        <property name="validationQueryTimeout">
            <value>10</value>
        </property>
        <property name="connectionProperties">
            <value>${jdbc.connectionProperties}</value> 
        </property>
        <!-- add propertis -->
        <property name="testWhileIdle">
            <value>true</value> 
        </property>
        <property name="maxWaitMillis">
            <value>${jdbc.maxWait:30000}</value>
        </property>
        <property name="timeBetweenEvictionRunsMillis">
            <value>${jdbc.timeBetweenEvictionRunsMillis:600000}</value> 
        </property>
        <property name="minEvictableIdleTimeMillis">
            <value>${jdbc.minEvictableIdleTimeMillis:900000}</value> 
        </property>
    </bean>
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- <bean id="sessionFactory" class="org.springframework.orm.ibatis3.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="dataSource" ref="dataSource" />
        <property name="transactionFactoryClass">
            <value type="java.lang.Class">
                org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory
            </value>
        </property>
    </bean> -->
    <!-- 传统做法,需要一个个dao接口进行注入 -->
    <!-- <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.mybatis.config.UserDaoMapper"></property>
        <property name="sqlSessionFactory" ref="sessionFactory"></property>
    </bean>  -->

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.mybatis..*" />
        <property name="sqlSessionFactoryBeanName" value="sessionFactory" />
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>  

</beans>

jdbc.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&characterEncoding=utf-8 
jdbc.username=root
jdbc.password=1234
jdbc.validQuery=select 1
jdbc.connectionProperties=connectTimeout=15000;socketTimeout=15000;

几点解释:
1、apllication包含的基本东西有
(1)datasource,这个可以理解为spring中数据库的配置(注意这里的datasource不要和jdbc.properties弄混了,jdbc.properties是一种键值对的配置信息,是便于我们在application.xml文件中使用的一个文件,比如定义datasource)
(2)SqlSessionFactoryBean 可以看到,SqlSessionFactoryBean是以datasource作为自己的一个属性的,这个属性是必须的,其实另外还有一个属性configLocation,指明mybatis配置文件的路径, 如果基本的 MyBatis 配置需要改变, 那么这就是一个需要它的地方。 通常这会是<settings><typeAliases>的部分。因为我们这个项目没有mybatis配置文件,所以没有引入
(3)事务配置。事务配置里面的datasource属性必须和SqlSessionFactoryBean的datasource属性是同一个数据源,否则事务管理器就不能起作用了(整合了spring和mybatis之后,mybatis就加入到了spring的事务管理当中,事务创建之后,它的使用,提交或回滚都是透明化,我们不需要写额外的代码去管理)
(4)数据映射接口。在spring4.0及以上是以扫描器的形式定义接口
的,使用MapperScannerConfigure,只需要指定DAO接口所在包名, 查 找 类 路 径 下 的 映 射 器 并 自 动 将 它 们 创 建 成 MapperFactoryBean
2、context:annotation-config
它的作用是向Spring容器注册;

AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor PersistenceAnnotationBeanPostProcessor, RequiredAnnotationBeanPostProcessor

这4个BeanPostProcessor的作用是为了让系统识别相应的注解

例如:
   如果想使用@Autowired注解,需要在Spring容器中声明AutowiredAnnotationBeanPostProcessor Bean。传统的声明方式:<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
   如果想使用@PersistenceContext注解,需要在Spring容器中声明PersistenceAnnotationBeanPostProcessor Bean。传统的声明:
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
   如果想使用@Required注解,需要在Spring容器中声明RequiredAnnotationBeanPostProcessor Bean。传统声明方式:
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
   如果想使用@Resource、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor。传统申明方式:
<bean class="org.springframework.beans.factory.annotation.CommonAnnotationBeanPostProcessor"/>
所以,如果按照传统声明一条一条去声明注解Bean,就会显得十分繁琐。因此如果在Spring的配置文件中事先加上<context:annotation-config/>这样一条配置的话,那么所有注解的传统声明就可以被 忽略,即不用在写传统的声明,Spring会自动完成声明。

3、context:component-scan base-package=”com.mybatis”
<context:component-scan/>的作用是让Bean定义注解工作起来,也就是上述传统声明方式。 它的base-package属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。

另外,<context:component-scan/>不但启用了对类包进行扫描以实施注释启动Bean定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此当使用
<context:component-scan/> 后,就可以将 <context:annotation-config/>移除了。

总结:如果有多个配置文件,在最顶层的配置文件(启动类所在的配置文件)中加入
<context:component-scan base-package="com.xx.xx" />
比如如果项目中有mybatis和spring的配置文件,就要在spring的配置文件中加入这段配置

猜你喜欢

转载自blog.csdn.net/u014473112/article/details/75452260