当前位置: 代码迷 >> 综合 >> springBoot+mybatis实现多数据源配置
  详细解决方案

springBoot+mybatis实现多数据源配置

热度:68   发布时间:2023-09-05 19:39:19.0

第一步,pom.xml(因为这个项目测试多个知识点jar包引得比较多,比较乱,根据个人需求删除)

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>xm_demo</groupId><artifactId>xm_demo</artifactId><version>1.0-SNAPSHOT</version><name>xm_demo Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><!--Spring boot版本号--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><!--基础版本配置--><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><fastjson.version>1.2.33</fastjson.version><druid.version>1.0.14</druid.version><commons.fileupload.version>1.3.1</commons.fileupload.version><thymeleaf.version>3.0.8.RELEASE</thymeleaf.version><thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version><thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version></properties><dependencies><!--谷歌json数据格式化--><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.6.2</version></dependency><!-- CXF webservice --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-spring-boot-starter-jaxws</artifactId><version>3.1.11</version></dependency><!--thymeleaf页面标签--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!--使用非严格html5格式--><dependency><groupId>net.sourceforge.nekohtml</groupId><artifactId>nekohtml</artifactId><version>1.9.22</version></dependency><!--spring booot web 依赖关系--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--数据库连接配置,开始:--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.6</version></dependency><!--数据库连接配置,结束。--><dependency><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><version>11.2.0.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--mybatis-plus相关依赖--><!--<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.6</version></dependency>--><!-- <dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>2.4.2</version></dependency>--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><!-- <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>2.1.8</version></dependency>--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.41</version></dependency><!--httpclient支持--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.1</version></dependency><!--json对象依赖--><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><!--文件上传下载依赖--><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3</version></dependency><!-- xml解析 --><dependency><groupId>com.thoughtworks.xstream</groupId><artifactId>xstream</artifactId><version>1.4.3</version></dependency><!--quartz定时任务--><dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz</artifactId><version>2.2.3</version></dependency><dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz-jobs</artifactId><version>2.2.3</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><fork>true</fork></configuration></plugin></plugins><!--打包的时候把如下资源全部打到工程中--><resources><resource><directory>src/main/resources</directory><includes><include>*</include><include>**/*</include></includes><filtering>false</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build>
</project>

第二步,数据源配置

package com.xlt.jczb.config;import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import javax.sql.DataSource;/*** @Classname DataSourceConfig1* @Description 主数据源配置* @Date 2019/11/27 10:00* @Created by xm*/@Configuration
// 配置主数据源mapper位置
@MapperScan(basePackages = "com.xlt.jczb.mapper", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSourceConfig1 {// 将这个对象放入Spring容器中@Bean(name = "test1DataSource")// 表示这个数据源是默认数据源@Primary@ConfigurationProperties(prefix = "spring.datasource.test1")public DataSource getDateSource1() {return DataSourceBuilder.create().build();}@Bean(name = "test1SqlSessionFactory")@Primarypublic SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource)throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(datasource);bean.setMapperLocations(// 设置mybatis的xml所在位置new PathMatchingResourcePatternResolver().getResources("classpath:/com/xlt/jczb/mapper/xml/*.xml"));return bean.getObject();}@Bean("test1SqlSessionTemplate")@Primarypublic SqlSessionTemplate test1sqlsessiontemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionfactory) {return new SqlSessionTemplate(sessionfactory);}
}
package com.xlt.jczb.config;import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import javax.sql.DataSource;/*** @Classname DataSourceConfig2* @Description 第二数据源配置* @Date 2019/11/27 10:13* @Created by xm*/
@Configuration
@MapperScan(basePackages = "com.xlt.jczb.mapper2", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSourceConfig2 {@Bean(name = "test2DataSource")@ConfigurationProperties(prefix = "spring.datasource.test2")public DataSource getDateSource2() {return DataSourceBuilder.create().build();}@Bean(name = "test2SqlSessionFactory")public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource datasource)throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(datasource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/com/xlt/jczb/mapper2/xml/*.xml"));return bean.getObject();}@Bean("test2SqlSessionTemplate")public SqlSessionTemplate test2sqlsessiontemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sessionfactory) {return new SqlSessionTemplate(sessionfactory);}
}

第三步,持久层

springBoot+mybatis实现多数据源配置

主数据源

package com.xlt.jczb.mapper;import com.xlt.jczb.entity.Xtzjgl;
import org.springframework.stereotype.Service;import java.util.List;/*** 系统自检管理** @date 2019-11-22 10:18:48* @author xm*/
@Service
public interface XtzjglMapper  {/*** 查询更新* @param xtzjgl*/void updateTime (Xtzjgl xtzjgl);/*** 查询所有* @param* @return*/List<Xtzjgl> getList();/*** 查询需要消息推送列表* @param* @return*/List<Xtzjgl> sendMsgList(Xtzjgl xtzjgl);}

xtzjglMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xlt.jczb.mapper.XtzjglMapper"><resultMap id="BaseResultMap" type="com.xlt.jczb.entity.Xtzjgl"><id column="ID" jdbcType="VARCHAR" property="id" /><result column="JWD" jdbcType="VARCHAR" property="jwd" /><result column="ZBC" jdbcType="VARCHAR" property="zbc" /><result column="NAME" jdbcType="VARCHAR" property="name" /><result column="TNAME" jdbcType="VARCHAR" property="tname" /><result column="CNAME" jdbcType="VARCHAR" property="cname" /><result column="MAXTIME" jdbcType="VARCHAR" property="maxtime" /><result column="ZBC_NAME" jdbcType="VARCHAR" property="zbcName" /><result column="UPDATETIME" jdbcType="VARCHAR" property="updateTime" /></resultMap><!-- 数据更新 --><update id="updateTime"  parameterType="com.xlt.jczb.entity.Xtzjgl">update xtzjgl set updatetime= #{updateTime}, maxtime=(select max(${cname})  from ${tname} where${zbcName}=#{zbc} ) where tName=#{tname} and cName=#{cname} and zbc=#{zbc}</update><!--查询所有配置信息--><select id="getList" resultMap="BaseResultMap" >select jwd,zbc,cname,tname, zbc_name from xtzjgl</select><!--查询所有需要信息发送列表--><select id="sendMsgList" resultMap="BaseResultMap" parameterType="com.xlt.jczb.entity.Xtzjgl">select jwd,zbc,tname, name from xtzjgl where MAXTIME is NULL or MAXTIME &lt; #{updateTime}</select>
</mapper>

第二数据源

package com.xlt.jczb.mapper2;import com.xlt.jczb.entity.Xtzjgl;
import org.springframework.stereotype.Service;/*** 系统自检管理** @date 2019-11-22 10:18:48* @author xm*/
//@Service
public interface XtzjglMapper2 {/*** 查询更新* @param xtzjgl*/void updateTime(Xtzjgl xtzjgl);/*** 多数据源链接测试* @param xtzjgl*/void updateTest(Xtzjgl xtzjgl);
}

xtzjglMapper2.xml 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xlt.jczb.mapper2.XtzjglMapper2"><resultMap id="BaseResultMap" type="com.xlt.jczb.entity.Xtzjgl"><id column="ID" jdbcType="VARCHAR" property="id" /><result column="JWD" jdbcType="VARCHAR" property="jwd" /><result column="ZBC" jdbcType="VARCHAR" property="zbc" /><result column="NAME" jdbcType="VARCHAR" property="name" /><result column="TNAME" jdbcType="VARCHAR" property="tname" /><result column="CNAME" jdbcType="VARCHAR" property="cname" /><result column="MAXTIME" jdbcType="VARCHAR" property="maxtime" /><result column="ZBC_NAME" jdbcType="VARCHAR" property="zbcName" /></resultMap><!-- 数据更新 --><update id="updateTime"  parameterType="com.xlt.jczb.entity.Xtzjgl">update xtzjgl set maxtime=(select max(${cname})  from ${tname} where${zbcName}=#{zbc} ) where tName=#{tname} and cName=#{cname} and zbc=#{zbc}</update><!--多数据源测试链接--><update id="updateTest"  parameterType="com.xlt.jczb.entity.Xtzjgl">update xtzjgl set jwd= #{jwd} where zbc= #{zbc}</update>
</mapper>

第四步,业务层

package com.xlt.jczb.service;import com.xlt.jczb.entity.Xtzjgl;import java.util.List;/*** <p>* 系统自检管理业务实现* </p>** @author 徐明明* @date 2019-11-22 10:21:22*/public interface XtzjglService  {/*** 查询更新* @param xtzjgl*/void updateTime (Xtzjgl xtzjgl);/*** 查询所有* @param* @return*/List<Xtzjgl> getList();/*** 查询需要消息推送列表* @param* @return*/List<Xtzjgl> sendMsgList(Xtzjgl xtzjgl);/*** 多数据源链接测试* @param xtzjgl*/void updateTest(Xtzjgl xtzjgl);}
package com.xlt.jczb.service.impl;import com.xlt.jczb.entity.Xtzjgl;
import com.xlt.jczb.mapper.XtzjglMapper;
import com.xlt.jczb.mapper2.XtzjglMapper2;
import com.xlt.jczb.service.XtzjglService;
import com.xlt.jczb.util.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;/*** <p>* 系统自检管理* </p>** @author 徐明明* @date 2019/07/24*/
@Service
public class XtzjglServiceImpl  implements XtzjglService {private static final Logger log=LoggerFactory.getLogger(XtzjglServiceImpl.class);//消息发送地址@Value("${sendMsgUrl}")private String sendMsgUrl;//整备场ID@Value("${baseInfo.zbcid}")private String deptid;//系统自检持久层@Autowiredprivate XtzjglMapper xtzjglMapper;//第二数据源@Autowiredprivate XtzjglMapper2 xtzjglMapper2;/*** 系统自检数据更新* @param xtzjgl*/@Overridepublic void updateTime(Xtzjgl xtzjgl) {xtzjglMapper.updateTime(xtzjgl);}@Overridepublic List<Xtzjgl> getList() {return xtzjglMapper.getList();}@Overridepublic List<Xtzjgl> sendMsgList(Xtzjgl xtzjgl) {return xtzjglMapper.sendMsgList(xtzjgl);}@Overridepublic void updateTest(Xtzjgl xtzjgl) {xtzjglMapper2.updateTest(xtzjgl);}}

第五步,前端控制器

package com.xlt.xfzb.controller;import com.xlt.xfzb.entity.Xtzjgl;
import com.xlt.xfzb.service.XtzjglService;
import com.xlt.xfzb.service.impl.XtzjglServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;/*** <p>** </p>** @author 徐明明* @date 2019/07/24*/
@Controller
@CrossOrigin
@RequestMapping("Xtzjgl")
public class XtzjglController {@Autowiredprivate XtzjglService xtzjglService;/*** 测试接口** @return*/@GetMapping("save")public ResponseEntity save(Xtzjgl xtzjgl) {System.out.println("执行了!!!!!!");//查询主库数据List<Xtzjgl> test = xtzjglService.getTest();//更新到第二数据源xtzjglService.updateTest(test.get(0));return new ResponseEntity("成功!!",HttpStatus.OK);}}

第六步,application.yml

server:port: 8081 # 应用程序监听的web端口max-http-header-size: 4048576spring:#应用名称application:name: scheduling_xfzb#配置文件profiles:active: dev#页面模板thymeleaf:mode: LEGACYHTML5cache: falsecontent-type: text/htmlencoding: UTF-8#附件上传大小限制http:multipart:maxRequestSize: 100MBmaxFileSize: 100MBmax-file-size: 100MB #上传文件的大小限定max-request-size: 100MB #上传请求数据的大小限定

application-dev.yml


#多数据源配置
spring:datasource:test1:username: xfzbpassword: xfzburl: jdbc:oracle:thin:@127.0.0.1:1521:swwgorcldriver-class-name: oracle.jdbc.driver.OracleDriverdruid:initial-size: 5test2:username: xazbpassword: xazburl: jdbc:oracle:thin:@127.0.0.1:1521:swwgorcldriver-class-name: oracle.jdbc.driver.OracleDriverdruid:initial-size: 6

配置完毕,想配置更多数据源,都是相同套路,去测试一下呗!

  相关解决方案