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

前言:我们在平常工作中用到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

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值