【MyBatis + Spring整合开发】(四)Mapper动

2019-02-26  本文已影响0人  花无缺_0159

复制上一节中的项目MyBatis_Spring_Mapper,命名为MyBatis_Spring_MapperScaner。

修改Spring主配置文件applicationContext.xml。

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
    
    <!-- 读取db.properties -->
    <context:property-placeholder location="db.properties"/>
    
    <!-- 配置c3p0连接池 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <!-- 配置mybatis sqlSessionFactory -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源  -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 告诉spring mybatis的核心配置文件 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    </bean>
    
    <!-- mapper动态扫描开发 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.mapper"/>
    </bean>
    
</beans>

推荐修改MapperTest.java里的一个小细节。

UserMapper mapper = (UserMapper) ac.getBean("userMapper");

改为

UserMapper mapper = ac.getBean(UserMapper.class);

进行测试。

测试结果

本系列【MyBatis + Spring整合开发】到此结束。

上一篇 下一篇

猜你喜欢

热点阅读