当前位置: 首页 > 科技观察

Springboot的Mybatis多数据源配置

时间:2023-03-12 16:34:45 科技观察

最近在项目开发中,需要为一个使用MySQL数据库的SpringBoot项目添加一个新的PLSQL数据库数据源,于是需要SpringBoot的多数据源开发。代码很简单,下面是实现过程。环境准备实验环境:JDK1.8SpringBoot2.4.1Maven3.6.3MySQL5.7由于我本地只有MySQL数据库,为了演示方便,我就在本地启动一个MySQL,在MySQL中创建两个数据库,每个库表一个示范用途。准备数据的本地MySQL端口默认不变,端口号为3306。创建数据库demo1、demo2。在demo1数据库中创建表book。--createtablecreatetableBook(idintauto_incrementprimarykey,authorvarchar(64)notnullcomment'作者信息',namevarchar(64)notnullcomment'书名',pricedecimalnotnullcomment'价格',createTimedatetimenullcomment'上架时间',descriptionvarchar(128)nullcomment'书名描述');--insertdataINSERTINTOdemo1.Book(id,author,name,price,createTime,description)VALUES(1,'金庸','笑傲江湖',13,'2020-12-1915:26:51','武侠小说');INSERTINTOdemo1.Book(id,author,name,price,createTime,description)VALUES(2,'洛贯中','三国演义',14,'2020-12-1915:28:36','历史小说');在demo2数据库中创建表用户。--createtablecreatetableUser(idintauto_incrementprimarykey,namevarchar(32)nullcomment'用户名',birthdaydatenullcomment'出生日期')comment'用户信息表';--insertdataINSERTINTOdemo2.User(id,name,birthday)VALUES(1,'金庸','1924-03-10');INSERTINTOdemo2.User(id,name,birthday)VALUES(2,'罗贯中','1330-01-10');数据准备完成,表中新增两条数据。项目准备这里初始化一个SpringBoot项目,直接从Spring官网添加web、lombok、mybatis、mysql依赖。访问直接下载:https://start.spring.io/starter.zip?type=maven-project&language=java&bootVersion=2.4.1.RELEASE&baseDir=demo&groupId=com&artifactId=wdbyte&name=demo&description=Demo%20project%20for%20Spring%20Boot&packageName=com.wdbyte.demo&packaging=jar&javaVersion=1.8&dependencies=mybatis,lombok,web,mysql如果你已经有一个SpringBoot项目,既然你要将其改造为多数据源,那么你应该已经有数据源了,如果新增的数据源数据库与当前数据库一致,可以直接使用你的项目进行改造测试。多数据源SpringBoot的多数据源开发非常简单。如果多个数据源的数据库相同,比如MySQL,那么依赖不需要做任何改动,只需要配置多数据源即可。如果你的新数据库的数据源与当前数据库不同,记得引入新数据库的驱动依赖,如MySQL、PGSQL等。mysqlmysql-connector-java运行时org.postgresqlpostgresql42.2.7由于连接配置中有多个数据源,由于数据库用户名和密码可能不同,所以需要配置多个数据源信息,直接在properties/yml中配置即可。这里要注意根据配置的属性名来区分,因为数据源必须有一个默认的数据源,所以最好从名称上区分(这里使用primary作为主要的数据源标识)。###########################主要数据源####################################spring.datasource.primary.jdbc-url=jdbc:mysql://127.0.0.1:3306/demo1?characterEncoding=utf-8&serverTimezone=GMT%2B8spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driversspring.datasource.primary.username=rootspring.datasource.primary.password=###########################第二个数据源#################################spring.datasource.datasource2.jdbc-url=jdbc:mysql://127.0.0.1:3306/demo2?characterEncoding=utf-8&serverTimezone=GMT%2B8spring.datasource.datasource2.driver-class-name=com.mysql.jdbc.Driverspring.datasource.datasource2.username=rootspring.datasource.datasource2.password=#mybatismybatis.mapper-locations=classpath:mapper/*.xmlmybatis.type-aliases-package=com.wdbyte.domain注意配置中数据源连接url结尾使用jdbc-url。因为使用了Mybatis框架,所以Mybatis框架的配置信息也是必不可少的。在扫描目录mapper下指定mapperxml配置文件。Mybatis配置如何编写MybatisMapper或者如何使用工具生成MybatisMapper不是本文的重点。不知道的可以参考Mybatis官方文档或者我之前的文章。链接一:使用Mybatis(自动生成的插件)访问数据库链接二:使用Mybatis集成pagehelper分页插件和mapper插件下面我已经根据上面两个表格写了对应的Mybatis配置图书馆,书籍和用户表。创建BookMapper.xml和UserMapper.xml,放在配置文件configuration的pathmapper目录下。在不同目录创建UserMapper和BookMapper接口操作类。这里注意,Mapper接口要根据数据源放在不同的目录下。以后最好使用不同的数据源配置扫描不同的目录,这样不同的Mapper可以使用不同的数据源配置。Service层没有变化,BookMapper和UserMapper都有一个selectAll()方法用于查询测试。上面的多数据源配置大家应该都看过了。到目前为止,与Mybatis单一数据源的写法唯一不同的是Mapper接口是使用不同的目录来分隔的,所以这种不同肯定会体现在数据源的配置上。主数据源开始配置两个数据源信息,首先配置主数据源,将扫描到的MapperScan目录配置为com.wdbyte.mapper.primary/***主数据源配置**@authorniujinpeng*@website:https://www.wdbyte.com*@date2020/12/19*/@Configuration@MapperScan(basePackages={"com.wdbyte.mapper.primary"},sqlSessionFactoryRef="sqlSessionFactory")publicclassPrimaryDataSourceConfig{@Bean(name="dataSource")@ConfigurationProperties(prefix="spring.datasource.primary")@PrimarypublicDataSourcedataSource(){returnDataSourceBuilder.create().build();}@Bean(name="sqlSessionFactory")@PrimarypublicSqlSessionFactorysqlSessionFactory(@Qualifier("dataSource")DataSourcedataSourcethrowsException{SqlSessionFactoryBeanbean=newSqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(newPathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));returnbean.getObject();}@Bean(名称="事务管理器")@PrimarypublicDataSourceTransactionManagertransactionManager(@Qualifier("dataSource")DataSourcedataSource){returnnewDataSourceTransactionManager(dataSource);}@Bean(name="sqlSessionTemplate")@PrimarypublicSqlSessionTemplatesqlSessionTemplate(@Qualifier("sqlSessionFactory")SqlSessionFactorysqlSessionFactory){returnnewSqlSessionTemplate(sqlSessionFactory);}}和数据映射source的区别是这里单独配置了dataSourcesqlSessionFactorytransactionManagersqlSessionTemplate,简单的bean创建,下面是使用的一些注解@ConfigurationProperties(prefix="spring.datasource.primary"):使用spring.datasource.primary开头的配置。@Primary:声明这是一个主数据源(默认数据源),这对于多数据源配置是必不可少的。@Qualifier:显式选择传入的bean。第二个数据源和主数据源唯一的区别是MapperScan扫描路径和创建的Bean的名称,没有主数据源的@Primary注解。/***第二个数据源配置**@authorniujinpeng*@website:https://www.wdbyte.com*@date2020/12/19*/@Configuration@MapperScan(basePackages={"com.wdbyte.mapper.datasource2"},sqlSessionFactoryRef="sqlSessionFactory2")publicclassSecondDataSourceConfig{@Bean(name="dataSource2")@ConfigurationProperties(prefix="spring.datasource.datasource2")publicDataSourcedataSource(){returnDataSourceBuilder.create().build();}@Bean(name="sqlSessionFactory2")publicSqlSessionFactorysqlSessionFactory(@Qualifier("dataSource2")DataSourcedataSource)throwsException{SqlSessionFactoryBeanbean=newSqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(newPathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));returnbean.getObject();}@Bean(name="transactionManager2")publicDataSourceTransactionManagertransactionManager(@Qualifier("dataSource2")DataSourcedataSource){returnnewDataSourceTransactionManager(dataSource);}@Bean(name="sqlSessionTemplate2")publicSqlSessionTemplatesqlSessionTemplate(@Qualifier("sqlSessionFactory2")SqlSessionFactorysqlSessionFactory){returnnewSqlSessionTemplate(sqlSessionFactory);}}注:因为scanMapper路径中配置了两个数据源,如果之前在SpringBoot的启动类中使用过Mapper扫描注解,则需要删除访问测试,写两个简单的查询Controller,然后进行访问测试。//BookController@RestControllerpublicclassBookController{@AutowiredprivateBookServicebookService;@GetMapping(value="/books")publicResponseselectAll()throwsException{Listbooks=bookService.selectAll();returnResponseUtill.success(books);}}//UserController@RestControllerpublicclassUserController{@AutowiredprivateUserServiceuserService;@ResponseBody@GetMapping(value="/users")publicResponseselectAll(){ListuserList=userService.selectAll();returnResponseUtill.success(userList);}}接入测试,这里我直接CURL请求。?~curllocalhost:8080/books{"code":"0000","message":"success","data":[{"id":1,"author":"金庸","name":"笑傲江湖","价格":13,"createtime":"2020-12-19T07:26:51.000+00:00","description":"武侠小说"},{"id":2,"作者":"洛贯中","name":"三国之恋","价格":14,"createtime":"2020-12-19T07:28:36.000+00:00","description":"历史小说"}]}?~curllocalhost:8080/users{"code":"0000","message":"success","data":[{"id":1,"name":"金庸""birthday":"1924-03-09T16:00:00.000+00:00"},{"id":2,"name":"罗贯中","birthday":"1330-01-09T16:00:00.000+00:00"}]}?~至此多数据源配置完成,测试成功。连接池其实在多数据源的改造中,我们一般不会使用默认的JDBC连接方式,往往需要引入连接池来进行连接优化,否则可能会经常遇到数据源连接被断开等错误日志。其实数据源切换连接池数据源很简单,直接引入连接池依赖,然后用创建连接池数据源代替创建dataSource。以阿里的Druid为例,先介绍连接池数据源依赖。com.alibabadruid添加Druid的一些配置。spring.datasource.datasource2.initialSize=3#根据自己的情况设置spring.datasource.datasource2.minIdle=3spring.datasource.datasource2.maxActive=20,重写dataSourceBean的创建代码部分。@Value("${spring.datasource.datasource2.jdbc-url}")privateStringurl;@Value("${spring.datasource.datasource2.driver-class-name}")privateStringdriverClassName;@Value("${spring.datasource.datasource2.username}")privateStringusername;@Value("${spring.datasource.datasource2.password}")privateStringpassword;@Value("${spring.datasource.datasource2.initialSize}")privateintinitialSize;@Value("${spring.datasource.datasource2.minIdle}")privateintminIdle;@Value("${spring.datasource.datasource2.maxActive}")privateintmaxActive;@Bean(name="dataSource2")publicDataSourcedataSource(){DruidDataSourcedataSource=newDruidDataSource();dataSource.setUrl(url);dataSource.setDriverClassName(driverClassName);dataSource.setUsername(用户名);dataSource.setPassword(密码);dataSource.setInitialSize(initialSize);dataSource.setMinIdle(minIdle);dataSource.setMaxActive(maxActive);返回数据源;}【编辑推荐】2021年更适合web开发的7种编程语言Eclipse和VSCode为什么不好用?权威数据来了,中国到底有多少程序员?10个实用工具网站你收藏了吗?2021年可能有五种编程语言前景更好