Spring整合MyBatis

1. 整合 Spring
    1). 加入 Spring 的 jar 包和配置文件
    2). 加入 mybatis 的 jar 包和配置文件: 实际上需要配置的就是 settings 的部分。
    3). 加入数据库驱动和数据库连接池的 jar 包
    4). 在 Spring 的配置文件中配置数据源.
    5). 在 Spring 的配置文件中配置 SqlSessionFactory
     【整合目标:在spring的配置文件中配置SqlSessionFactory以及让mybatis用上spring的声明式事务】     

<context:component-scan base-package="com.neuedu.mybatis" />
        <context:property-placeholder location="classpath:jdbc.properties"/>
        
        <bean id="dataSource"
            class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="user" value="${jdbc.user}"></property>
            <property name="password" value="${jdbc.password}"></property>
            <property name="driverClass" value="${jdbc.driverClass}"></property>
            <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>    
        </bean>
        
        <!-- 对于 mybatis 而言,使用的事务管理器是 DataSourceTransactionManager -->    
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>

        <tx:annotation-driven />

        <!-- 配置 SqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!-- 配置 mybatis 配置文件的位置和名称 -->
            <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        </bean>

        <!-- 扫描 Mapper 接口,并把它们纳入到 IOC 容器中 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.neuedu.mybatis" />
        </bean>
    
    6)在mybatis的全局配置文件中配置settings属性
        <configuration>
            <settings>
                <setting name="mapUnderscoreToCamelCase" value="true"/>
            </settings>
        </configuration>               

2. 最终整合的结果:可以从 IOC 容器中获取 Mapper,然后直接调用 Mapper 的方法。
    注意:几乎不直接调用 SqlSession 的任何方法.

参考:mybatis和spring相关

原文地址:https://www.cnblogs.com/kangxingyue-210/p/7475234.html