其他分享
首页 > 其他分享> > mybaits整合的两种方式

mybaits整合的两种方式

作者:互联网

xml形式整合spring和mybaits

1.sqlSessionFactory的配置

        1.xml文件的路径 

         2.dataSource (mybaits要查询数据库,所以dataSource是必须要的,用于连接数据库的配置)

<!-- sqlSessionFactory 1.spring-mybaits整合-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载 MyBatis 的配置文件 -->
        <!--<property name="configLocation" value="SqlMapConfig.xml"/>-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>

        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

2.MapperScannerConfigurer的配置 

        我们mapper接口的路径

 <!-- Mapper 扫描器  2.spring-mybaits整合-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描 cn.wmyskxz.mapper 包下的组件 -->
        <property name="basePackage" value="com.tx.mapper"/>
    </bean>

注解的方式

1.SqlsessionFactory的配置 (跟上面的xml一致,需要以下两个配置),扫描配置信息

  1.xml文件的路径 

         2.dataSource        

  /**
     * 注意:这里是spring-mybaits整合里面的xm文件配置信息
     * 1.配置数据源
     * 2.扫描xml文件并解析
    * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean // 带参数的bean ,有参数的bean方法。 spring会从ioc中找对应的bean注入,如果ico中没有会报错
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //这里配置xml扫描文件的信息
        sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml")); //mybatis的xml文件路径
        return  sessionFactoryBean;
    }

2.配置路径和sqlSessionFactory

      进入注解会发现 底层也向spring注册了MapperScannerConfigurer 类

@MapperScan(basePackages ="com.transcaltion.dao",sqlSessionFactoryRef="sqlSessionFactory")

补充: 

        进入到@MapperScan注解

 进入MapperScannerRegistrar类该类 实现 

ImportBeanDefinitionRegistrar接口 所以会调用 registerBeanDefinitions方法 (Bean工厂的后置处理器)

该方法里面就是把 

MapperScannerConfigurer  类注册到我们的Bean定义信息里面,这个类就是上面我们xml里面配置的类

 

了解了上面两种方式对于之后看源码和springboot自动装配之mybaits会很有很好的作用

后续我会更新mybaits-autoconfiguration

标签:xml,两种,spring,配置,sessionFactoryBean,mybaits,dataSource,整合
来源: https://blog.csdn.net/sunshinezx8023/article/details/121145801