Spring和Mybatis整合,配置文件

整合时除了未整合前spring、mybatis的必须包外还需要加入两个包

spring-jdbc-4.2.5.RELEASE.jar

mybatis-spring-1.2.5.jar

spring-jdbc-4.2.5.RELEASE.jar 提供了Mybatis所用数据源的管理

mybatis-spring-1.2.5.jar 提供了myBatis所用的sqlSessionFactionBean 和SqlSessionTemplate

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 自动装配配置 -->
    <bean
        class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    <!-- 数据源Bean配置 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/appproject" />
        <property name="username" value="root" />
        <property name="password" value="12345678" />
    </bean>
    <!-- MyBatis session工厂bean配置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath*:mappers/mapper-*.xml"></property>
    </bean>
    <!-- 创建session bean,自动装配 -->
    <bean class="org.mybatis.spring.SqlSessionTemplate" autowire="byType">
        <constructor-arg ref="sqlSessionFactory"></constructor-arg>
    </bean>
    <import resource="beans-dao.xml" />
    <import resource="beans-service.xml" />

</beans>
org.springframework.jdbc.datasource.DriverManagerDataSource类是spring-jdbc提供的数据源对象,我们创建SqlSessionTemplate时用的是这个类的构造方法,传入的参数的类型是SqlSessionFactionBean,这个Bean是由mybatis-spring提供的。
SqlSessionTemplate使用了自动装配的方式(代码如下),我的Dao层有一个基类,基类中的SqlSessionTemplate 已经用@Autowired。Spring启动时,会自动注入,想要了解自动装配的方式请点击我的另外一篇博客@Autowired的使用
public class BaseDao {
    @Autowired
    protected  SqlSessionTemplate session;
}

 当然,整合的方式有很多种,此处是其中之一。

原文地址:https://www.cnblogs.com/doublejun/p/5387732.html