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()]);
    }
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM