ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Spring Boot MyBatis配置Druid多数据源

Spring Boot MyBatis配置Druid多数据源 一、引入依赖dependencygroupIdcom.oracle/groupIdartifactIdojdbc6/artifactIdversion6.0/version/dependencydependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdscoperuntime/scope/dependencydependencygroupIdorg.mybatis.spring.boot/groupIdartifactIdmybatis-spring-boot-starter/artifactIdversion2.1.1/version/dependencydependencygroupIdcom.alibaba/groupIdartifactIddruid-spring-boot-starter/artifactIdversion1.1.22/version/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependency二、多数据源配置在Spring Boot配置文件application.yml中配置多数据源和Spring Boot JdbcTemplate配置Druid多数据源一致。然后根据application.yml创建两个数据源配置类MysqlDatasourceConfig和OracleDatasourceConfigMysqlDatasourceConfigConfigurationMapperScan(basePackagesMysqlDatasourceConfig.PACKAGE,sqlSessionFactoryRefmysqlSqlSessionFactory)publicclassMysqlDatasourceConfig{// mysqldao扫描路径staticfinalStringPACKAGEcom.wno704.boot.mysqldao;// mybatis mapper扫描路径staticfinalStringMAPPER_LOCATIONclasspath:mapper/mysql/*.xml;PrimaryBean(namemysqldatasource)ConfigurationProperties(spring.datasource.druid.mysql)publicDataSourcemysqlDataSource(){returnDruidDataSourceBuilder.create().build();}Bean(namemysqlTransactionManager)PrimarypublicDataSourceTransactionManagermysqlTransactionManager(){returnnewDataSourceTransactionManager(mysqlDataSource());}Bean(namemysqlSqlSessionFactory)PrimarypublicSqlSessionFactorymysqlSqlSessionFactory(Qualifier(mysqldatasource)DataSourcedataSource)throwsException{finalSqlSessionFactoryBeansessionFactorynewSqlSessionFactoryBean();sessionFactory.setDataSource(dataSource);//如果不使用xml的方式配置mapper则可以省去下面这行mapper location的配置。sessionFactory.setMapperLocations(newPathMatchingResourcePatternResolver().getResources(MysqlDatasourceConfig.MAPPER_LOCATION));returnsessionFactory.getObject();}}上面代码配置了一个名为mysqldatasource的数据源对应application.yml中spring.datasource.druid.mysql前缀配置的数据库。然后创建了一个名为mysqlSqlSessionFactory的Bean并且注入了mysqldatasource。与此同时还分别定了两个扫描路径PACKAGE和MAPPER_LOCATION前者为Mysql数据库对应的mapper接口地址后者为对应的mapper xml文件路径。Primary标志这个Bean如果在多个同类Bean候选时该Bean优先被考虑。多数据源配置的时候必须要有一个主数据源用Primary标志该Bean。同理接着配置Oracle数据库对应的配置类OracleDatasourceConfigConfigurationMapperScan(basePackagesOracleDatasourceConfig.PACKAGE,sqlSessionFactoryReforacleSqlSessionFactory)publicclassOracleDatasourceConfig{// oracledao扫描路径staticfinalStringPACKAGEcom.wno704.boot.oracledao;// mybatis mapper扫描路径staticfinalStringMAPPER_LOCATIONclasspath:mapper/oracle/*.xml;Bean(nameoracledatasource)ConfigurationProperties(spring.datasource.druid.oracle)publicDataSourceoracleDataSource(){returnDruidDataSourceBuilder.create().build();}Bean(nameoracleTransactionManager)publicDataSourceTransactionManageroracleTransactionManager(){returnnewDataSourceTransactionManager(oracleDataSource());}Bean(nameoracleSqlSessionFactory)publicSqlSessionFactoryoracleSqlSessionFactory(Qualifier(oracledatasource)DataSourcedataSource)throwsException{finalSqlSessionFactoryBeansessionFactorynewSqlSessionFactoryBean();sessionFactory.setDataSource(dataSource);//如果不使用xml的方式配置mapper则可以省去下面这行mapper location的配置。sessionFactory.setMapperLocations(newPathMatchingResourcePatternResolver().getResources(OracleDatasourceConfig.MAPPER_LOCATION));returnsessionFactory.getObject();}}具体的application.yml配置如下spring:datasource:druid:# 数据库访问配置, 使用druid数据源mysql:type:com.alibaba.druid.pool.DruidDataSourcedriver-class-name:com.mysql.cj.jdbc.Driverurl:jdbc:mysql://127.0.0.1:3306/springboot?useUnicodetruecharacterEncodingutf8serverTimezoneUTCallowMultiQueriestrueuseSSLfalseusername:springpassword:spring#123oracle:type:com.alibaba.druid.pool.DruidDataSourcedriver-class-name:oracle.jdbc.driver.OracleDriverurl:jdbc:oracle:thin:125.72.228.21:1521:testdbusername:wno704password:wno704db312# 连接池配置initial-size:5min-idle:5max-active:20# 连接等待超时时间max-wait:30000# 配置检测可以关闭的空闲连接间隔时间time-between-eviction-runs-millis:60000# 配置连接在池中的最小生存时间min-evictable-idle-time-millis:300000validation-query:select 1 from dualtest-while-idle:truetest-on-borrow:falsetest-on-return:false# 打开PSCache并且指定每个连接上PSCache的大小pool-prepared-statements:truemax-open-prepared-statements:20max-pool-prepared-statement-per-connection-size:20# 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, wall用于防火墙filters:stat,wall# Spring监控AOP切入点如x.y.z.service.*,配置多个英文逗号分隔aop-patterns:com.springboot.service.*# WebStatFilter配置web-stat-filter:enabled:true# 添加过滤规则url-pattern:/*# 忽略过滤的格式exclusions:*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*# StatViewServlet配置stat-view-servlet:enabled:true# 访问路径为/druid时跳转到StatViewServleturl-pattern:/druid/*# 是否能够重置数据reset-enable:false# 需要账号密码才能访问控制台login-username:druidlogin-password:druid123# IP白名单# allow: 127.0.0.1# IP黑名单共同存在时deny优先于allow# deny: 192.168.1.218# 配置StatFilterfilter:stat:log-slow-sql:true脚本导入myslq脚本参考《Spring-Boot整合MyBatis》oracle脚本导入CREATETABLEWNO704.STUDENT(SNONUMBERNOTNULL,SNAMENVARCHAR2(50),SSEXNVARCHAR2(2),CONSTRAINTPK_STUDENT_SNOPRIMARYKEY(SNO))tablespaceWNO704 PCTFREE10initrans1maxtrans255storage(INITIAL768Knext8K minextents1MAXEXTENTS unlimited t8K minextents1MAXEXTENTS unlimited);COMMENTONCOLUMNWNO704.STUDENT.SNOIS学号;COMMENTONCOLUMNWNO704.STUDENT.SNAMEIS姓名;COMMENTONCOLUMNWNO704.STUDENT.SSEXIS性别;INSERTINTOSTUDENTVALUES(1,KangKang,M);INSERTINTOSTUDENTVALUES(2,Mike,M);INSERTINTOSTUDENTVALUES(3,Jane,F);三、编码配置完多数据源接下来分别在com.springboot.mysqldao路径和com.springboot.oracledao路径下创建两个mapper接口MysqlStudentMapperMapperRepository(mysqlStudentMapper)publicinterfaceMysqlStudentMapper{ListMapString,ObjectgetAllStudents();}OracleStudentMapperMapperRepository(oracleStudentMapper)publicinterfaceOracleStudentMapper{ListMapString,ObjectgetAllStudents();}接着创建mapper接口对应的实现在src/main/resource/mapper/mysql/路径下创建MysqlStudentMapper.xml?xml version1.0 encodingUTF-8 ?!DOCTYPEmapperPUBLIC-//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtdmappernamespacecom.wno704.boot.mysqldao.MysqlStudentMapperselectidgetAllStudentsresultTypejava.util.Mapselect * from student/select/mapper在src/main/resource/mapper/oracle/路径下创建OracleStudentMapper.xml?xml version1.0 encodingUTF-8 ?!DOCTYPEmapperPUBLIC-//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtdmappernamespacecom.wno704.boot.oracledao.OracleStudentMapperselectidgetAllStudentsresultTypejava.util.Mapselect * from student/select/mapper编写StudentServicepublicinterfaceStudentService{ListMapString,ObjectgetAllStudentsWithMysql();ListMapString,ObjectgetAllStudentsWithOracle();}编写实现类StudentServiceImplService(studentService)publicclassStudentServiceImplimplementsStudentService{AutowiredprivateMysqlStudentMappermysqlStudentMapper;AutowiredprivateOracleStudentMapperoracleStudentMapper;OverridepublicListMapString,ObjectgetAllStudentsWithMysql(){returnthis.mysqlStudentMapper.getAllStudents();}OverridepublicListMapString,ObjectgetAllStudentsWithOracle(){returnthis.oracleStudentMapper.getAllStudents();}}四、测试编写controller测试RestControllerpublicclassTestController{AutowiredprivateStudentServicestudentService;RequestMapping(value/getAllStudentsWithMysql,methodRequestMethod.GET)publicListMapString,ObjectgetAllStudentsWithMysql(){returnthis.studentService.getAllStudentsWithMysql();}RequestMapping(value/getAllStudentsWithOracle,methodRequestMethod.GET)publicListMapString,ObjectgetAllStudentsWithOracle(){returnthis.studentService.getAllStudentsWithOracle();}}最终项目目录如下图所示启动项目访问http://localhost:8080/getAllStudentsWithMysqlhttp://localhost:8080/getAllStudentsWithOracle
返回列表