多数据源切换

多数据源切换

  • jdbcTemplate
    • 二级目录
      • 三级目录
  • jdbcTemplate
  • 使用切面
  • mybatis层次的多数据源
  • spring的dynamic自动注入

jdbcTemplate

二级目录

三级目录

项目中经常会有多个数据源,那么如何处理呢
有4种方法
准备:
创建两个数据库

CREATE SCHEMA `test` DEFAULT CHARACTER SET utf8mb4 ;
CREATE SCHEMA `school` DEFAULT CHARACTER SET utf8mb4 ;

test数据库创建user表,school数据库创建student表

--
-- Table structure for table `user`
--DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `user` (`id` int NOT NULL AUTO_INCREMENT,`username` varchar(100) NOT NULL COMMENT '用户名',`real_name` varchar(200) DEFAULT NULL COMMENT '真实姓名',`password` varchar(2000) NOT NULL COMMENT '密码',`sex` tinyint(1) NOT NULL COMMENT '性别:0-男,1-女',`birthday` date NOT NULL COMMENT '生日',`card_id` varchar(20) NOT NULL COMMENT '身份证号',`phone` varchar(20) NOT NULL COMMENT '手机号',PRIMARY KEY (`id`),UNIQUE KEY `card_id` (`card_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户表';
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `user`
--LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'liming','黎明','123456',1,'2000-09-09','623001200010014433','13099890032'),(3,'miaoshanshan','苗姗姗','123456',0,'2001-10-12','314002200110125523','13509327765');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;--
-- Host: localhost    Database: school
-- ------------------------------------------------------
-- Server version	8.0.29--
-- Table structure for table `student`
--DROP TABLE IF EXISTS `student`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `student` (`id` int NOT NULL AUTO_INCREMENT,`student_name` varchar(100) NOT NULL COMMENT '学生姓名',`student_no` varchar(20) DEFAULT NULL COMMENT '学号',`password` varchar(200) NOT NULL COMMENT '密码',`sex` tinyint(1) NOT NULL COMMENT '性别:0-男,1-女',`birthday` date NOT NULL COMMENT '生日',`card_id` varchar(20) NOT NULL COMMENT '身份证号',PRIMARY KEY (`id`),UNIQUE KEY `student_no` (`student_no`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='学生表';
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `student`
--LOCK TABLES `student` WRITE;
/*!40000 ALTER TABLE `student` DISABLE KEYS */;
INSERT INTO `student` VALUES (1,'黎明','202110010101','123456',1,'2000-09-09','623001200010014433'),(2,'李艳','202110010102','123456',1,'2000-03-19',''),(3,'苗姗姗','202110010302','123456',0,'2001-10-12','314002200110125523'),(4,'李媛','202110010301','123456',0,'2002-11-22','314002200211225523');
/*!40000 ALTER TABLE `student` ENABLE KEYS */;
UNLOCK TABLES;

jdbcTemplate

不需要特殊的jar,只需配置即可
pom文件

<?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>org.example</groupId><artifactId>jdbc-test</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.5.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.3.5.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.17</version></dependency></dependencies>
</project>

配置多个数据源

server:port: 10010
spring:application:name: dynamic-datasource-jdbcdatasource:master:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: rootschool:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/school?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: root

对数据源进行配置

package com.test.jdbc.config;import com.zaxxer.hikari.HikariDataSource;
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.jdbc.core.JdbcTemplate;import javax.sql.DataSource;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-09 20:51*/
@Configuration
public class DataSourceConfig {@Primary@Bean("master")@ConfigurationProperties("spring.datasource.master")public DataSource masterDataSource(){return DataSourceBuilder.create().type(HikariDataSource.class).build();}@Bean("school")@ConfigurationProperties("spring.datasource.school")public DataSource schoolDataSource(){return DataSourceBuilder.create().type(HikariDataSource.class).build();}@Bean("master")public JdbcTemplate masterTemplate(@Qualifier("master") DataSource dataSource){return new JdbcTemplate(dataSource);}@Bean("schoolTemplate")public JdbcTemplate schoolTemplate(@Qualifier("school") DataSource dataSource){return new JdbcTemplate(dataSource);}
}

启动类,因为用knife做测试,所以需要@EnableOpenApi

package com.test.jdbc;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-11 20:33*/
@SpringBootApplication
@EnableOpenApi
public class JdbcService {public static void main(String[] args) {SpringApplication.run(JdbcService.class,args);}
}

分别写实体,接口及实现类进行测试
实体类

package com.test.jdbc.domain;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;import java.io.Serializable;
import java.sql.Date;/*** 学生表* @TableName student*/
@Data
public class Student implements Serializable {/*** id*/@TableId(type = IdType.AUTO)private Integer id;/*** 学生姓名*/private String studentName;/*** 学号*/private String studentNo;/*** 密码*/private String password;/*** 性别:0-男,1-女*/private Boolean sex;/*** 生日*/private Date birthday;//java.sql.Date对应数据库date类型,只显示年月日/*** 身份证号*/private String cardId;/*** 手机号*/@TableField(exist = false)@JsonIgnoreprivate String phone;}package com.test.jdbc.domain;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;import java.io.Serializable;
import java.sql.Date;/*** 用户表* @TableName user*/
@Data
public class User implements Serializable {/*** id*/@TableId(type = IdType.AUTO)private Integer id;/*** 用户名*/private String username;/*** 真实姓名*/private String realName;/*** 密码*/private String password;/*** 性别:0-男,1-女*/private Boolean sex;/*** 生日*/private Date birthday;//java.sql.Date对应数据库date类型,只显示年月日/*** 身份证号*/private String cardId;/*** 手机号*/private String phone;private static final long serialVersionUID = 1L;
}

接口

package com.test.jdbc.controller;import com.test.jdbc.domain.Student;
import com.test.jdbc.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-11 20:31*/
@RestController
public class TestController {@Autowiredprivate JdbcTemplate masterTemplate;@Autowiredprivate JdbcTemplate schoolTemplate;@GetMapping("getUserList")public List<User> getUserList(){List<User> list = masterTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));return list;}@GetMapping("getStudentList")public List<Student> getStudentList(){List<Student> students = schoolTemplate.query("select * from student", new BeanPropertyRowMapper<>(Student.class));return students;}@GetMapping("getStudent")public List<Student> getStudent(){String sql = "select * from student";List<Student> list = schoolTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));list.stream().forEach(student -> {if (StringUtils.isNotBlank(student.getCardId())){String phone = masterTemplate.queryForObject("select phone from user where card_id = ?",String.class);student.setPhone(phone);}});return list;}
}

浏览器输入http://localhost:10010/doc.html
在这里插入图片描述
在这里插入图片描述

使用切面

需要额外写注解
pom

<?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>org.example</groupId><artifactId>aop-test</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.5.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.3.5.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.17</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId><version>2.2.6.RELEASE</version></dependency></dependencies>
</project>

配置文件

server:port: 10011
spring:application:name: dynamic-datasource-aopdatasource:master:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: rootschool:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/school?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: root

启动类

package com.test.aop;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import springfox.documentation.oas.annotations.EnableOpenApi;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-09 20:37*/
@EnableOpenApi
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//排除数据源自动注入,不然会报错
public class AopSourceService {public static void main(String[] args) {SpringApplication.run(AopSourceService.class,args);}
}

自定义注解

package com.test.aop.annonation;import java.lang.annotation.*;@Target({ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSourceSwitch {public String dataSourceName() default "";
}

自定义注解的切面实现

package com.test.aop.aop;import com.test.aop.annonation.DataSourceSwitch;
import com.test.aop.config.DynamicDataSourceHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;import java.lang.reflect.Method;@Aspect
@Component
public class DataSourceAspect {@Pointcut("@annotation(com.test.aop.annonation.DataSourceSwitch)")public void pointCut(){}@Before("pointCut()")public void before(JoinPoint joinpoint){MethodSignature signature = (MethodSignature)joinpoint.getSignature();Method method = signature.getMethod();DataSourceSwitch annotation = method.getAnnotation(DataSourceSwitch.class);DynamicDataSourceHolder.setDatasourcePool(annotation.dataSourceName());}@After("pointCut()")public void after(){DynamicDataSourceHolder.removeDatasourcePool();}
}

数据源配置类

package com.test.aop.config;import com.test.aop.enums.DataSourceType;
import com.zaxxer.hikari.HikariDataSource;
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 javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-09 20:51*/
@Configuration
public class DataSourceConfig {@Bean("masterDataSource")@ConfigurationProperties("spring.datasource.master")public DataSource masterDataSource(){return DataSourceBuilder.create().type(HikariDataSource.class).build();}@Bean("schoolDataSource")@ConfigurationProperties("spring.datasource.school")public DataSource schoolDataSource(){return DataSourceBuilder.create().type(HikariDataSource.class).build();}@Primary@Bean("dynamicDataSource")public DynamicDataSource dynamicDataSource(){Map<Object,Object> targetDataSources = new HashMap<>();targetDataSources.put(DataSourceType.TEST.name(),masterDataSource());targetDataSources.put(DataSourceType.SCHOOL.name(),schoolDataSource());return new DynamicDataSource(masterDataSource(),targetDataSources);}/*@Bean("masterTemplate")public JdbcTemplate masterTemplate(@Qualifier("masterDataSource") DataSource dataSource){return new JdbcTemplate(dataSource);}@Bean("schoolTemplate")public JdbcTemplate schoolTemplate(@Qualifier("schoolDataSource") DataSource dataSource){return new JdbcTemplate(dataSource);}*/
}package com.test.aop.config;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import javax.sql.DataSource;
import java.util.Map;public class DynamicDataSource extends AbstractRoutingDataSource {public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object,Object> targetDataSource){super.setDefaultTargetDataSource(defaultTargetDataSource);super.setTargetDataSources(targetDataSource);super.afterPropertiesSet();}@Overrideprotected Object determineCurrentLookupKey() {return DynamicDataSourceHolder.getDatasourcePool();}
}package com.test.aop.config;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-09 20:54*/
public class DynamicDataSourceHolder {public static ThreadLocal<String> DATASOURCE_POOL = new ThreadLocal<>();/*** 获取数据源变量* @return*/public static String getDatasourcePool(){return DATASOURCE_POOL.get();}/*** 设置数据源变量* @param name*/public static void setDatasourcePool(String name){DATASOURCE_POOL.set(name);}public static void removeDatasourcePool(){DATASOURCE_POOL.remove();}
}

数据源类型枚举

package com.test.aop.enums;public enum DataSourceType {TEST,SCHOOL,;
}

接口或实现类使用注解

package com.test.aop.controller;import com.test.aop.annonation.DataSourceSwitch;
import com.test.aop.domain.Student;
import com.test.aop.domain.User;
import com.test.aop.service.StudentService;
import com.test.aop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-09 20:58*/@RestController
public class TestController {@Autowiredprivate UserService userService;@Autowiredprivate StudentService studentService;@GetMapping("user/list")public List<User> userList(){return userService.list();}@GetMapping("student/list")@DataSourceSwitch(dataSourceName = "SCHOOL")public List<Student> studentList(){return studentService.list();}@PostMapping("user/save")public void saveUser(@RequestBody User user){userService.save(user);}@PostMapping("student/save")@DataSourceSwitch(dataSourceName = "SCHOOL")public void saveStudent(@RequestBody Student student){studentService.save(student);}@GetMapping("registerToUser")public void registerToUser(Integer id,String username,String phone,String cardId){userService.registerTiUser(id,username,phone,cardId);}/**** @return*/@GetMapping("list")public List<Student> list(){return studentService.getPhone();}
}

mybatis层次的多数据源

需要每个库写一个配置类
pom

server:port: 10012
spring:application:name: dynamic-datasource-mybatisdatasource:master:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: rootschool:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/school?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: root

启动类

package com.test.mybatis;import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import springfox.documentation.oas.annotations.EnableOpenApi;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-11 21:06*/
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, MybatisPlusAutoConfiguration.class})
@EnableOpenApi
public class MybatisService {public static void main(String[] args) {SpringApplication.run(MybatisService.class,args);}
}

数据源配置文件

package com.test.mybatis.config;import com.sun.tracing.ProbeName;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
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.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;import javax.sql.DataSource;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-11 21:14*/
@Configuration
@MapperScan(basePackages = "com.test.mybatis.mapper.test",sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {@Bean@ConfigurationProperties("spring.datasource.master")public DataSource masterDatasource(){return DataSourceBuilder.create().type(HikariDataSource.class).build();}@Primary@Beanpublic SqlSessionFactory masterSqlSessionFactory()throws Exception{SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(masterDatasource());return bean.getObject();}@Primary@Beanpublic DataSourceTransactionManager masterTransactionManager(){DataSourceTransactionManager manager = new DataSourceTransactionManager();manager.setDataSource(masterDatasource());return manager;}@Beanpublic TransactionTemplate masterTemplate(){return new TransactionTemplate(masterTransactionManager());}}package com.test.mybatis.config;import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
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.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;import javax.sql.DataSource;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2023-11-11 21:14*/
@Configuration
@MapperScan(basePackages = "com.test.mybatis.mapper.school",sqlSessionFactoryRef = "schoolSqlSessionFactory")
public class SchoolDataSourceConfig {@Bean@ConfigurationProperties("spring.datasource.school")public DataSource schoolDatasource(){return DataSourceBuilder.create().type(HikariDataSource.class).build();}@Beanpublic SqlSessionFactory schoolSqlSessionFactory()throws Exception{SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(schoolDatasource());return bean.getObject();}@Beanpublic DataSourceTransactionManager schoolTransactionManager(){DataSourceTransactionManager manager = new DataSourceTransactionManager();manager.setDataSource(schoolDatasource());return manager;}@Beanpublic TransactionTemplate schoolTemplate(){return new TransactionTemplate(schoolTransactionManager());}}

spring的dynamic自动注入

需要引入dynamic-datasource-spring-boot-starter,实现类使用注解@DS(“数据源”)即可
pom

<?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>org.example</groupId><artifactId>spring-jdbc</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.5.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.3.5.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>2.5.6</version></dependency></dependencies>
</project>

配置文件有点不同

server:port: 10013
spring:application:name: dynamic-datasource-springdatasource:dynamic:primary: masterdatasource:master:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: rootschool:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/school?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: root

启动类

@SpringBootApplication
@EnableOpenApi
public class SpringAutoService{public static void main(String[] args) {SpringApplication.run(SpringAutoService.class,args);}
}

在实现类使用注解

package com.test.spring.service.impl;import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.spring.domain.Student;
import com.test.spring.mapper.StudentMapper;
import com.test.spring.mapper.UserMapper;
import com.test.spring.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/**
*
*/
@Service
@DS("school")
public class StudentServiceImpl extends ServiceImpl<StudentMapper,Student> implements StudentService{@Autowiredprivate UserMapper userMapper;@Overridepublic List<Student> getPhone() {List<Student> list = list();list.stream().filter(student -> StringUtils.isNotBlank(student.getCardId())).forEach(student -> {String phone = userMapper.selectPhoneByCardId(student.getCardId());student.setPhone(phone);});return list;}}
package com.test.spring.service.impl;import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.spring.domain.Student;
import com.test.spring.domain.User;
import com.test.spring.mapper.StudentMapper;
import com.test.spring.mapper.UserMapper;
import com.test.spring.service.StudentService;
import com.test.spring.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/**
*
*/
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{@Autowiredprivate UserMapper userMapper;@Autowiredprivate StudentMapper studentMapper;@Overridepublic void registerTiUser(Integer id, String username, String phone, String cardId) {Student student = studentMapper.selectById(id);if (null == student){throw new RuntimeException("该学生不存在");}User user = new User();user.setRealName(student.getStudentName());BeanUtils.copyProperties(student,user);user.setUsername(username);user.setPhone(phone);user.setCardId(cardId);userMapper.insert(user);}}

源码地址:https://gitee.com/qfp17393120407/dynamic-datasource-new.git

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/139594.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Django中如何创建表关系,请求生命周期流程图

Django中ORM创建表关系 如何创建表关系(一对一 &#xff0c; 一对多 &#xff0c; 多对多) 图书表&#xff0c;出版社表&#xff0c;作者表&#xff0c;作者详情表 换位思考法判断表关系 图书表和出版社表 >>> 一对多 >>> 图书表是多&#xff0c;出…

GCC工具详解【Linux知识贩卖机】

很多人在喧嚣声中登场&#xff0c;也有少数人在静默中退出。 --单独中的洞见2 文章目录 简介程序到可执行文件链接动态链接和静态链接动态库和静态库动态库和静态库的打包打包静态库打包动态库选项 -static 总结 简介 GCC&#xff08;GNU Compiler Collection&#xff09; 是一…

计算机中丢失mfc140u.dll怎么解决

mfc140u.dll是一个Microsoft Visual C库文件&#xff0c;主要用于MFC&#xff08;Microsoft Foundation Class&#xff09;应用程序的开发。它包含了MFC应用程序所需的一些常用功能&#xff0c;如对话框、窗口、菜单等。当mfc140u.dll丢失时&#xff0c;可能会导致MFC应用程序无…

思科9300交换机使用USB进行升级ISO

一、下载ISO 一、网址 Software Download - Cisco Systems 二、找到型号 四、选择XE 软件 五、进行下载 二、COPY 进 U盘 一、、请注意&#xff01;如果你的U盘不是Fat32文件格式则交换机读取不了&#xff0c;请先格式化再复制文件。 二、下载后将 bin文件复制到U盘。 1.扩展…

idea Plugins 搜索不到插件

Settings — System Settings — HTTP Proxy&#xff0c;打开HTTP Proxy 页面&#xff0c;设置自动发现代理&#xff1a; 勾选Atuto-detect proxy settings&#xff0c;勾选Automatic proxy configuration URL&#xff0c;输入&#xff1a; https://plugins.jetbrains.com/id…

【Python】AppUI自动化—appium自动化元素定位、元素事件操作(17)下

文章目录 前言一.Appium 元素定位1.定位方式种类2.如何定位2.1 id定位2.2 className定位2.3 content-desc 定位2.4 Android Uiautomator定位4.1 text定位4.2 text模糊定位4.3 text正则匹配定位4.4 resourceId定位4.5 resourceId正则匹配定位4.6 className定位4.7 className正则…

No184.精选前端面试题,享受每天的挑战和学习

🤍 前端开发工程师(主业)、技术博主(副业)、已过CET6 🍨 阿珊和她的猫_CSDN个人主页 🕠 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 🍚 蓝桥云课签约作者、已在蓝桥云课上架的前后端实战课程《Vue.js 和 Egg.js 开发企业级健康管理项目》、《带你从入…

适用于初学者的 .NET MAUI

适用于初学者的 .NET MAUI | Microsoft Learn 记录微软Learn中用到的代码。文章比较粗糙&#xff0c;大部分是项目代码粘贴。想详细学习的可到上面的链接学习&#xff0c;代码可以从这里复制后直接运行。 练习中一共有两个页面&#xff1a; 1、MainPage.xaml 用于添加列表中的…

No182.精选前端面试题,享受每天的挑战和学习

🤍 前端开发工程师(主业)、技术博主(副业)、已过CET6 🍨 阿珊和她的猫_CSDN个人主页 🕠 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 🍚 蓝桥云课签约作者、已在蓝桥云课上架的前后端实战课程《Vue.js 和 Egg.js 开发企业级健康管理项目》、《带你从入…

【Unity实战】实现强大通用易扩展的对话系统(附项目源码)

文章目录 先看看实现的最终效果前言素材前期准备工作1. 简单绘制地形2. 绘制对话框3. 配置人物动画4. 实现简单的控制人物移动 控制对话框的显示隐藏定义对话内容实现简单的对话功能逐字打印效果按下按键快速显示文本实现多个NPC配置不同对话扩展TextAsset 读取文档文件实际应用…

No183.精选前端面试题,享受每天的挑战和学习

🤍 前端开发工程师(主业)、技术博主(副业)、已过CET6 🍨 阿珊和她的猫_CSDN个人主页 🕠 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 🍚 蓝桥云课签约作者、已在蓝桥云课上架的前后端实战课程《Vue.js 和 Egg.js 开发企业级健康管理项目》、《带你从入…

Mac电脑配置Flutter开发环境

1.进入官网下载页&#xff1a; Flutter SDK releases | Flutter 可以看到有 Windows、macOS、Linux三种系统的下载包 选择macOS&#xff0c;然后点击下载 Stable channel&#xff08;稳定版&#xff09;中的最新版本&#xff0c;下载完成后可以移动到资源库Library中。 2.下载…

TCP触发海康扫码相机S52CN-IC-JQR-NNN25

PC环境设置 为保证客户端正常运行以及数据传输的稳定性&#xff0c;在使用客户端软件前&#xff0c;需要对 PC 环境 进行设置 关闭防火墙 操作步骤如下&#xff1a; 1. 打开系统防火墙。 2. 在自定义设置界面中&#xff0c;选择关闭防火墙的对应选项&#xff0c;并单击…

74hc595模块参考

74hc595模块参考 8位串行并行输出&#xff08;SIPO&#xff09;移位寄存器 使用74HC595移位寄存器扩展微控制器上的输出引脚数量。如果你需要扩充输入引脚的数量那么你需要74HC165移位寄存器。 SER&#xff08;串行输入&#xff09;引脚用于一次一位地将数据发送到移位寄存器…

快速教程|如何在 AWS EC2上使用 Walrus 部署 GitLab

Walrus 是一款基于平台工程理念的开源应用管理平台&#xff0c;致力于解决应用交付领域的深切痛点。借助 Walrus 将云原生的能力和最佳实践扩展到非容器化环境&#xff0c;并支持任意应用形态统一编排部署&#xff0c;降低使用基础设施的复杂度&#xff0c;为研发和运维团队提供…

459. 重复的子字符串

459. 重复的子字符串 原题链接&#xff1a;完成情况&#xff1a;解题思路&#xff1a;参考代码&#xff1a;__459重复的子字符串_枚举__459重复的子字符串_字符串匹配__459重复的子字符串_KMP算法__459重复的子字符串_优化的KMP算法 错误经验吸取 原题链接&#xff1a; 459. …

酷开科技持续推动智能投影行业创新发展

近年来&#xff0c;投影仪逐渐成为年轻人追捧的家居时尚单品。据国际数据公司&#xff08;IDC&#xff09;报告显示&#xff0c;2022年中国投影机市场总出货量505万台&#xff0c;超80%为家用投影仪。相比于电视&#xff0c;投影仪外观小巧、屏幕大小可调节&#xff0c;无论是卧…

OpenCV:图像旋转与缩放

人工智能的学习之路非常漫长&#xff0c;不少人因为学习路线不对或者学习内容不够专业而举步难行。不过别担心&#xff0c;我为大家整理了一份600多G的学习资源&#xff0c;基本上涵盖了人工智能学习的所有内容。点击下方链接,0元进群领取学习资源,让你的学习之路更加顺畅!记得…

从白日梦到现实:推出 Elastic 的管道查询语言 ES|QL

作者&#xff1a;George Kobar, Bahubali Shetti, Mark Settle 今天&#xff0c;我们很高兴地宣布 Elastic 的新管道查询语言 ES|QL&#xff08;Elasticsearch 查询语言&#xff09;的技术预览版&#xff0c;它可以转换、丰富和简化数据调查。 ES|QL 由新的查询引擎提供支持&am…

vmware16.2内部win7联网

1、主机配置 前置条件&#xff1a;DHCP和NAT服务已启动 设置无线IP与虚拟机IP为自动获取 二者都是&#xff1a;右键-属性 选择IPv4 自动获取 2、虚拟机配置 设置虚拟机上网方式为NAT 菜单栏-虚拟机-设置 NMnet8改为NAT模式 菜单栏-编辑-虚拟网络编辑器 win7系统内部网…