前言:我們在平常工作中用到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()]); }