springboot + mybatis 多数据源配置
1.测试项目分布:
2.测试数据库分布:
有两个数据库
1.main
2.second
3.项目yml配置文件:
server:
port: 8888
servlet:
context-path: / #项目路径
spring:
datasource:
main: #主数据源配置
username: root
password: 123456
jdbc-url: jdbc:mysql://localhost:3306/main?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
second: #次数据源配置
username: root
password: 123456
jdbc-url: jdbc:mysql://localhost:3306/second?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/**/*Mapper.xml
type-aliases-package: club.jiajiajia.demo.entity
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #sql日志打印
call-setters-on-nulls: true #解决返回类型为Map的时候如果值为null将不会封装此字段
#日志
logging:
level:
club:
jiajiajia:
demo:
mapper: debug
上述两个数据源分别是
main: #主数据源配置
second: #次数据源配置
4.主数据源的配置类:
package club.jiajiajia.demo.config.datasource;
import javax.sql.DataSource;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;
/**
* 主数据源配置
* @Configuration 表示这个类为一个配置类
* @MapperScan 配置mybatis的接口类放的地方
* @author jiajia
*/
@Configuration
@MapperScan(basePackages = "club.jiajiajia.demo.mapper.main", sqlSessionFactoryRef = "mainSqlSessionFactory")
public class MainDataSourceConfig {
/**
* @Bean 将这个对象放入Spring容器中
* @ConfigurationProperties 配置文件中的数据源连接配置
* @return
*/
@Bean(name = "mainDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.main")
public DataSource getDateSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "mainSqlSessionFactory")
@Primary
public SqlSessionFactory mainSqlSessionFactory(@Qualifier("mainDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
/**
* 设置mybatis的xml所在位置
*/
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/mainMapper/*.xml"));
return bean.getObject();
}
@Bean("mainSqlSessionTemplate")
@Primary
public SqlSessionTemplate mainsqlsessiontemplate(
@Qualifier("mainSqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
5.次数据源的配置类
package club.jiajiajia.demo.config.datasource;
import javax.sql.DataSource;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;
/**
* 次数据源配置
* @Configuration 表示这个类为一个配置类
* @MapperScan 配置mybatis的接口类放的地方
* @author jiajia
*/
@Configuration
@MapperScan(basePackages = "club.jiajiajia.demo.mapper.second", sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {
/**
* @Bean 将这个对象放入Spring容器中
* @ConfigurationProperties 配置文件中的数据源连接配置
* @return
*/
@Bean(name = "secondDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource getDateSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondSqlSessionFactory")
@Primary
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
/**
* 设置mybatis的xml所在位置
*/
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/secondMapper/*.xml"));
return bean.getObject();
}
@Bean("secondSqlSessionTemplate")
@Primary
public SqlSessionTemplate secondsqlsessiontemplate(
@Qualifier("secondSqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
配置解释:
主数据源的配置会扫描club.jiajiajia.demo.mapper.main文件夹下的接口,和mapper/mainMapper文件夹下的配置xml文件
次数据源的配置会扫描club.jiajiajia.demo.mapper.second文件夹下的接口,和mapper/secondMapper文件夹下的xml配置文件
注意:如果项目只配置了这些,启动项目时会报错
解决办法就是在启动类上加配置:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
这样就不会报错了
6.测试:
controller层
package club.jiajiajia.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 多数据源测试
* @author jiajia
*/
import club.jiajiajia.demo.entity.Person;
import club.jiajiajia.demo.service.TestService;
import club.jiajiajia.demo.util.AjaxResult;
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("getPerson")
public AjaxResult getPerson(@RequestParam(name="id",required = true) int id) {
Person p=testService.getPerson(id);
return AjaxResult.success(p);
}
}
service层:
package club.jiajiajia.demo.service;
import club.jiajiajia.demo.entity.Person;
public interface TestService {
Person getPerson(int id);
}
package club.jiajiajia.demo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import club.jiajiajia.demo.entity.Person;
import club.jiajiajia.demo.mapper.main.TestMainMapper;
import club.jiajiajia.demo.mapper.second.TestSecondMapper;
import club.jiajiajia.demo.service.TestService;
@Service
public class TestServiceImpl implements TestService{
@Autowired
private TestMainMapper testMainMapper;
@Autowired
private TestSecondMapper testSecondMapper;
@Override
public Person getPerson(int id) {
// TODO Auto-generated method stub
Person p = testMainMapper.getPerson(id);
if(p!=null) {
p.setAddress(testSecondMapper.getAddress(id));
return p;
}else {
return null;
}
}
}
dao层
查询main数据库
package club.jiajiajia.demo.mapper.main;
import club.jiajiajia.demo.entity.Person;
public interface TestMainMapper {
Person getPerson(int id);
}
dao层配置文件 TestMainMapper .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="club.jiajiajia.demo.mapper.main.TestMainMapper">
<select id="getPerson" resultType="club.jiajiajia.demo.entity.Person">
select * from person where id=#{id}
</select>
</mapper>
查询second数据库
package club.jiajiajia.demo.mapper.second;
import java.util.List;
import club.jiajiajia.demo.entity.Address;
public interface TestSecondMapper {
List<Address> getAddress(int id);
}
dao层配置文件 TestSecondMapper .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="club.jiajiajia.demo.mapper.second.TestSecondMapper">
<select id="getAddress" resultType="club.jiajiajia.demo.entity.Address">
select * from address where user_id=#{id}
</select>
</mapper>
实体类
package club.jiajiajia.demo.entity;
public class Address {
private int id;
private String location;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Address() {
super();
// TODO Auto-generated constructor stub
}
}
package club.jiajiajia.demo.entity;
import java.util.List;
public class Person {
private int id;
private String name;
private String sex;
private List<Address> address;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
package club.jiajiajia.demo.util;
import java.io.Serializable;
public class AjaxResult implements Serializable{
private static final long serialVersionUID = 4404203832037984839L;
private Integer code;
private boolean success;
private String msg;
private Object data;
public AjaxResult(){
}
public AjaxResult(Integer code, boolean success, String msg, Object data){
this.code=code;
this.success = success;
this.msg = msg;
this.data = data;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public AjaxResult setCode(Integer code) {
this.code = code;
return this;
}
public static AjaxResult success(Object data){
return new AjaxResult(200,true, null, data);
}
public static AjaxResult success(Object data, String msg){
return new AjaxResult(200,true, msg, data);
}
public static AjaxResult success(String msg){
return new AjaxResult(200,true, msg, null);
}
public static AjaxResult fail(String msg){
return new AjaxResult(300,false, msg, null);
}
public static AjaxResult failLocation(Object data, String msg){
return new AjaxResult(300,false, msg, data);
}
}
启动类:
package club.jiajiajia.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MoreDataSourceTestApplication {
public static void main(String[] args) {
SpringApplication.run(MoreDataSourceTestApplication.class, args);
}
}
数据
访问接口
评论区
请写下您的评论...
猜你喜欢
java项目
1394
springboot+mybatis配置多数据源并利用aop实现自动切换(demo)
框架
1931
springboot+mybatis配置多数据源并利用aop实现自动切换1.项目大致结构2.pom依赖dependencygroupIdorg.springframework.boot
redis,springboot
1988
一、springboot集成redis一般配置pomdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot
official
889
[TOC]一、pom文件添加依赖dependencygroupIdorg.mybatis.spring.boot/groupIdartifactIdmybatis-spring-boot-starter/artifactIdversion2.1.4/version/dependencydependencygroupIdmysql/groupIdartifactIdmysql-connector-j
blog
springboot整合mybatis
框架
2780
springboot整合mybatis1.创建maven项目2.sql文件SETNAMESutf8mb4;SETFOREIGN_KEY_CHECKS=0
blog
mybatis缓存
框架
1657
询到的数据可能是一级缓存的数据不同的sqlSession使用同一个mapper时查询,查询到的数据可能是另一个sqlSession做相同操作留下的缓存如果你配置了二级缓存,那么查询数据的顺序应该为:二级
java序列化储存
2781
序列化和反序列化请参考:http://www.jiajiajia.club/blog/artical/yjw520/161源码下载地址:http://photo.jiajiajia.club
blog
mybatis遍历int数组
框架
1225
mybatis遍历int数组foreachcollection="ids"index="index"item="item" open="("separator=","close=")" #{item}/foreach
最新发表
归档
2018-11
12
2018-12
33
2019-01
28
2019-02
28
2019-03
32
2019-04
27
2019-05
33
2019-06
6
2019-07
12
2019-08
12
2019-09
21
2019-10
8
2019-11
15
2019-12
25
2020-01
9
2020-02
5
2020-03
16
2020-04
4
2020-06
1
2020-07
7
2020-08
13
2020-09
9
2020-10
5
2020-12
3
2021-01
1
2021-02
5
2021-03
7
2021-04
4
2021-05
4
2021-06
1
2021-07
7
2021-08
2
2021-09
8
2021-10
9
2021-11
16
2021-12
14
2022-01
7
2022-05
1
2022-08
3
2022-09
2
2022-10
2
2022-12
5
2023-01
3
2023-02
1
2023-03
4
2023-04
2
2023-06
3
2023-07
4
2023-08
1
2023-10
1
2024-02
1
2024-03
1
2024-04
1
2024-08
1
标签
算法基础
linux
前端
c++
数据结构
框架
数据库
计算机基础
储备知识
java基础
ASM
其他
深入理解java虚拟机
nginx
git
消息中间件
搜索
maven
redis
docker
dubbo
vue
导入导出
软件使用
idea插件
协议
无聊的知识
jenkins
springboot
mqtt协议
keepalived
minio
mysql
ensp
网络基础
xxl-job
rabbitmq
haproxy
srs
音视频
webrtc
javascript
加密算法
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。