SpringBoot+Mybatis加载Mapper.xml文件的两种方式

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

最近在整合shardingsphere 用到所以总结一下。

一、配置文件:

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://www.cnblogs.com/shanheyongmu/p/15560883.html