mybatis与spring结合使用

1、定义datasource


 

如:

 <bean id="propertyConfigurer"  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <value>classpath*:jdbc.properties</value>
            </property>
    </bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">  
         <property name="driverClassName" value="${jdbc.driverClassName}" />
         <property name="url" value="${jdbc.url}" />
         <property name="username" value="${jdbc.username}" />
         <property name="password" value="${jdbc.password}" />
    </bean>

2、定义SqlSessionFactory

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" /> 
        <!-- 文件映射器,指定类文件 可选-->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>  
        <!-- 自动扫描mapping.xml文件 可选-->  
        <property name="mapperLocations" value="classpath:com/chinasoft/ssm/mapper/*.xml"></property>  
    </bean> 

3、定义mapper接口


2种方式
第1种:扫描方式
 <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定扫描的包名
            如果扫描多个包,那么每个包中间使用半角逗号分隔 -->
        <property name="basePackage" value="com.yf.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

第2种:单独定义某个mapper接口bean
<!-- MapperFactoryBean:根据mapper接口生成的代理对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.ys.mapper.UserMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

参考:https://www.cnblogs.com/ysocean/p/7368499.html
https://www.cnblogs.com/feitianshaoxai/p/6605171.html
posted @ 2020-08-08 19:22  蓝天随笔  阅读(28)  评论(0编辑  收藏