欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot Mybatis如何配置多数据源并分包

程序员文章站 2022-05-25 22:10:03
看了不少网上关于多数据源的配置,大致可分为两类,分包方式和通过切面方式;样例已上传至github:https://github.com/dadachao/multids第一个子项目ds01即时使用分包...

看了不少网上关于多数据源的配置,大致可分为两类,分包方式和通过切面方式;

样例已上传至github:https://github.com/dadachao/multids

第一个子项目ds01即时使用分包方式完成多数据源配置。

总结项目中出现的问题和解决办法:

数据库的连接信息:

连接信息是写在db.properties文件中的:

#数据库ds1
spring.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.driver
spring.datasource.ds1.url=jdbc:mysql://localhost:3306/ds1?servertimezone=utc
spring.datasource.ds1.username=root
spring.datasource.ds1.password=root
#数据库ds2
spring.datasource.ds2.driver-class-name=com.mysql.cj.jdbc.driver
spring.datasource.ds2.url=jdbc:mysql://localhost:3306/ds2?servertimezone=utc
spring.datasource.ds2.username=root
spring.datasource.ds2.password=root

这些信息将在配置类dbconfig1.java中引用。一开始我是通过使用注解@importresource(...)引进db.properties文件,但在运行时报了org.xml.sax.saxparseexception; linenumber: 1; columnnumber: 1; 前言中不允许有内容的错误;使用这个注解也是我瞎猜的。后是通过使用注解@propertysource(value = "classpath:/db.properties",encoding = "utf-8")解决问题。

其次是关于在配置类中使用@configurationproperties注解自动注入连接信息值(value)的问题:spring.datasource.ds1.url=jdbc:mysql://localhost:3306/ds1?servertimezone=utc

注意要使用.url而不是.jdbc-url;

指定数据连接池类型datatype:

数据源类型可以在配置类生成datasource的方法中指定:

@bean(name = "ds1datasource")
  @primary
  @configurationproperties(prefix = "spring.datasource.ds1")
  public datasource getdatasource(){
    datasourcebuilder<?> datasourcebuilder = datasourcebuilder.create();
    datasourcebuilder.type(com.alibaba.druid.pool.druiddatasource.class);
    return datasourcebuilder.build();
  }

指定***mapper.xml文件的路径扫描问题:(相当重要)

使用配置类进行数据源相关进行配置后,原先在application.yml中配置的相关参数就不起作用了(原因未知),原先我是在application.yml中配置了.xml文件的扫描路径:

mybatis:
mapper-locations: classpath:/mybatis/**/*.xml
type-aliases-package: com.kong.ds01.model

但在运行时报错:mapper bound error(not found);后来通过在配置类中写入扫描路径解决:

public final static string mapperxmllocation = "classpath:mybatis/*/*.xml";

@bean(name = "ds1sqlsessionfactory")
  @primary
  public sqlsessionfactory getsqlsessionfactory(@qualifier("ds1datasource") datasource datasource) throws exception {
    sqlsessionfactorybean sqlsessionfactorybean = new sqlsessionfactorybean();
    sqlsessionfactorybean.setdatasource(datasource);
    sqlsessionfactorybean.setmapperlocations(new pathmatchingresourcepatternresolver().getresources(mapperxmllocation));
    return sqlsessionfactorybean.getobject();
  }

而且通过这种方法表示任意路径不能使用/**/,要使用/*/,否则识别不出来又会报相同的错误,这点真是太坑了!

指定执行器的类型(execute.type):

可以通过在配置类中的sqlsessiontemplate中指定:

@bean(name = "ds1sqlsessiontemplate")
  @primary
  public sqlsessiontemplate getsqlsessiontemplate(@qualifier("ds1sqlsessionfactory") sqlsessionfactory sqlsessionfactory){
    return new sqlsessiontemplate(sqlsessionfactory, executortype.batch);
  }

指定为batch类型后在进行批量操作时效率有明显的提高。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。