前言:我们在平常工作中用到mybatis去加载Mapper.xml文件,可能mapper文件放的路径不一样,由此我们需要配置多个路径,幸运的是Mybatis支持我们配置多个不同路径。现在介绍两种方法。

一、配置文件:

 

SpringBoot和Mybatis整合已经天然支持这种方式,只需要在配置文件添加多个路径用逗号隔开


mybatis:
  mapper-locations: classpath*:com/pab/cc/fas/mapper/*Mapper*.xml,classpath*:com/pab/cc/ces/mapper/*Mapper*.xml,classpath*:com/pab/cc/ams/mapper/*Mapper*.xml
  type-aliases-package: com.urthink.upfs.springbootmybatis.entity
  #IDENTITY: MYSQL #取回主键的方式
  #notEmpty: false #insert和update中,是否判断字符串类型!=''
  configuration:
    #进行自动映射时,数据以下划线命名,如数据库返回的"order_address"命名字段是否映射为class的"orderAddress"字段。默认为false
    map-underscore-to-camel-case: true
    # 输出SQL执行语句 (log4j2本身可以输出sql语句)


二、Javabean配置

主要用到的是SqlSessionFactoryBean的setMapperLocations(),这个方法需要传入resource数组。

 public SqlSessionFactory sqlSessionFactory() {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceOne());
        sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations());
        return sqlSessionFactoryBean.getObject();
    }

    public Resource[] resolveMapperLocations() {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath*:com/pab/cc/fas/mapper/*Mapper*.xml");
        mapperLocations.add("classpath*:com/pab/cc/ces/mapper/*Mapper*.xml");
        mapperLocations.add("classpath*:com/pab/cc/ams/mapper/*Mapper*.xml");
        List<Resource> resources = new ArrayList();
        if (mapperLocations != null) {
            for (String mapperLocation : mapperLocations) {
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException e) {
                    // ignore
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }

参考文献:https://blog.csdn.net/TreeShu321/article/details/104547973

基础:请参考:

SpringBoot+Mybatis(JavaConfig方式配置)

https://blog.csdn.net/qq_37598011/article/details/80669608

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐