本文源码:GitHub·点这里 || GitEE·点这里

一、项目案例简介

1、多数据简介

实际的项目中,经常会用到不同的数据库以满足项目的实际需求。随着业务的并发量的不断增加,一个项目使用多个数据库:主从复制、读写分离、分布式数据库等方式,越来越常见。

2、MybatisPlus简介

MyBatis-Plus(简称 MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。

插件特点

无代码侵入:只做增强不做改变,引入它不会对现有工程产生影响。
强大的 CRUD 操作:通过少量配置即可实现单表大部分 CRUD 操作满足各类使用需求。
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件。
支持主键自动生成:可自由配置,解决主键问题。
内置代码生成器:采用代码或者 Maven 插件可快速生成各层代码。
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作。
内置性能分析插件:可输出 Sql 语句以及其执行时间。

二、多数据源案例

1、项目结构

注意:mapper层和mapper.xml层分别放在不同目录下,以便mybatis扫描加载。

2、多数据源配置

spring:
# 数据源配置
datasource:
type: com.alibaba.druid.pool.DruidDataSource
admin-data:
driverClassName: com.mysql.jdbc.Driver
dbUrl: jdbc:mysql://127.0.0.1:3306/cloud-admin-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
username: root
password: 123
initialSize: 20
maxActive: 100
minIdle: 20
maxWait: 60000
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 30
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
maxEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1 FROM DUAL
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
filters: stat,wall
user-data:
driverClassName: com.mysql.jdbc.Driver
dbUrl: jdbc:mysql://127.0.0.1:3306/cloud-user-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
username: root
password: 123
initialSize: 20
maxActive: 100
minIdle: 20
maxWait: 60000
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 30
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
maxEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1 FROM DUAL
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
filters: stat,wall

这里参数的形式是多样的,只需要配置参数扫描即可。

3、参数扫描类

@Component
@ConfigurationProperties(prefix = "spring.datasource.admin-data")
public class DruidOneParam {
private String dbUrl;
private String username;
private String password;
private String driverClassName;
private int initialSize;
private int maxActive;
private int minIdle;
private int maxWait;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private int maxEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private String filters;
private String connectionProperties;
// 省略 GET 和 SET
}

4、配置Druid连接池

@Configuration
@MapperScan(basePackages = {"com.data.source.mapper.one"},sqlSessionTemplateRef = "sqlSessionTemplateOne")
public class DruidOneConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DruidOneConfig.class) ;
@Resource
private DruidOneParam druidOneParam ;
@Bean("dataSourceOne")
public DataSource dataSourceOne () {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(druidOneParam.getDbUrl());
datasource.setUsername(druidOneParam.getUsername());
datasource.setPassword(druidOneParam.getPassword());
datasource.setDriverClassName(druidOneParam.getDriverClassName());
datasource.setInitialSize(druidOneParam.getInitialSize());
datasource.setMinIdle(druidOneParam.getMinIdle());
datasource.setMaxActive(druidOneParam.getMaxActive());
datasource.setMaxWait(druidOneParam.getMaxWait());
datasource.setTimeBetweenEvictionRunsMillis(druidOneParam.getTimeBetweenEvictionRunsMillis());
datasource.setMinEvictableIdleTimeMillis(druidOneParam.getMinEvictableIdleTimeMillis());
datasource.setMaxEvictableIdleTimeMillis(druidOneParam.getMaxEvictableIdleTimeMillis());
datasource.setValidationQuery(druidOneParam.getValidationQuery());
datasource.setTestWhileIdle(druidOneParam.isTestWhileIdle());
datasource.setTestOnBorrow(druidOneParam.isTestOnBorrow());
datasource.setTestOnReturn(druidOneParam.isTestOnReturn());
datasource.setPoolPreparedStatements(druidOneParam.isPoolPreparedStatements());
datasource.setMaxPoolPreparedStatementPerConnectionSize(druidOneParam.getMaxPoolPreparedStatementPerConnectionSize());
try {
datasource.setFilters(druidOneParam.getFilters());
} catch (Exception e) {
LOGGER.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(druidOneParam.getConnectionProperties());
return datasource;
}
@Bean
public SqlSessionFactory sqlSessionFactoryOne() throws Exception{
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
factory.setDataSource(dataSourceOne());
factory.setMapperLocations(resolver.getResources("classpath*:/dataOneMapper/*.xml"));
return factory.getObject();
}
@Bean(name="transactionManagerOne")
public DataSourceTransactionManager transactionManagerOne(){
return new DataSourceTransactionManager(dataSourceOne());
}
@Bean(name = "sqlSessionTemplateOne")
public SqlSessionTemplate sqlSessionTemplateOne() throws Exception {
return new SqlSessionTemplate(sqlSessionFactoryOne());
}
}

注意事项

  • MapperScan 在指定数据源上配置;
  • SqlSessionFactory 配置扫描的Mapper.xml地址 ;
  • DataSourceTransactionManager 配置该数据源的事务;
  • 两个数据源的配置手法相同,不赘述 ;

5、操作案例

  • 数据源一:简单查询
@Service
public class AdminUserServiceImpl implements AdminUserService {
@Resource
private AdminUserMapper adminUserMapper ;
@Override
public AdminUser selectByPrimaryKey (Integer id) {
return adminUserMapper.selectByPrimaryKey(id) ;
}
}
  • 数据源二:事务操作
@Service
public class UserBaseServiceImpl implements UserBaseService {
@Resource
private UserBaseMapper userBaseMapper ;
@Override
public UserBase selectByPrimaryKey(Integer id) {
return userBaseMapper.selectByPrimaryKey(id);
}
// 使用指定数据源的事务
@Transactional(value = "transactionManagerTwo")
@Override
public void insert(UserBase record) {
// 这里数据写入失败
userBaseMapper.insert(record) ;
// int i = 1/0 ;
}
}

注意:这里的需要指定该数据源配置的事务管理器。

三、MybatisPlus案例

1、核心依赖

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7.1</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.0.7.1</version>
</dependency>

2、配置文件

mybatis-plus:
mapper-locations: classpath*:/mapper/*.xml
typeAliasesPackage: com.digital.market.*.entity
global-config:
db-config:
id-type: AUTO
field-strategy: NOT_NULL
logic-delete-value: -1
logic-not-delete-value: 0
banner: false
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'

3、分层配置

mapper层
UserBaseMapper extends BaseMapper<UserBase>
实现层
UserBaseServiceImpl extends ServiceImpl<UserBaseMapper,UserBase> implements UserBaseService
接口层
UserBaseService extends IService<UserBase>

4、mapper.xml文件

<mapper namespace="com.plus.batis.mapper.UserBaseMapper" >
<resultMap id="BaseResultMap" type="com.plus.batis.entity.UserBase" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="pass_word" property="passWord" jdbcType="VARCHAR" />
<result column="phone" property="phone" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
<result column="state" property="state" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, user_name, pass_word, phone, email, create_time, update_time, state
</sql>
<select id="selectByParam" parameterType="com.plus.batis.entity.QueryParam" resultMap="BaseResultMap">
select * from hc_user_base
</select>
</mapper>

注意事项

BaseMapper中的方法都已默认实现;这里也可以自定义实现一些自己的方法。

5、演示接口

@RestController
@RequestMapping("/user")
public class UserBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseController.class) ;
@Resource
private UserBaseService userBaseService ;
@RequestMapping("/info")
public UserBase getUserBase (){
return userBaseService.getById(1) ;
}
@RequestMapping("/queryInfo")
public String queryInfo (){
UserBase userBase1 = userBaseService.getOne(new QueryWrapper<UserBase>().orderByDesc("create_time")) ;
LOGGER.info("倒叙取值:{}",userBase1.getUserName());
Integer count = userBaseService.count() ;
LOGGER.info("查询总数:{}",count);
UserBase userBase2 = new UserBase() ;
userBase2.setId(1);
userBase2.setUserName("spring");
boolean resFlag = userBaseService.saveOrUpdate(userBase2) ;
LOGGER.info("保存更新:{}",resFlag);
Map<String, Object> listByMap = new HashMap<>() ;
listByMap.put("state","0") ;
Collection<UserBase> listMap = userBaseService.listByMap(listByMap) ;
LOGGER.info("ListByMap查询:{}",listMap);
boolean removeFlag = userBaseService.removeById(3) ;
LOGGER.info("删除数据:{}",removeFlag);
return "success" ;
}
@RequestMapping("/queryPage")
public IPage<UserBase> queryPage (){
QueryParam param = new QueryParam() ;
param.setPage(1);
param.setPageSize(10);
param.setUserName("cicada");
param.setState(0);
return userBaseService.queryPage(param) ;
}
@RequestMapping("/pageHelper")
public PageInfo<UserBase> pageHelper (){
return userBaseService.pageHelper(new QueryParam()) ;
}
}

这里pageHelper方法是使用PageHelper插件自定义的方法。

四、源代码地址

GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent

SpringBoot2 配置多数据源,整合MybatisPlus增强插件的更多相关文章

  1. (十六)配置多数据源,整合MybatisPlus增强插件

    配置多数据源,整合MybatisPlus增强插件 多数据简介 MybatisPlus简介 1.案例实现 1.1 项目结构 1.2 多数据源配置 1.3 参数扫描类 1.4 配置Druid连接池 1.5 ...

  2. 【2.0】SpringBoot2配置Druid数据源及监控

    什么是Druid? Druid首先是Java语言中最好的数据库连接池,也是阿里巴巴的开源项目.Druid是阿里巴巴开发的号称为监控而生的数据库连接池,在功能.性能.扩展性方面,都超过其他数据库连接池, ...

  3. SpringBoot整合MyBatisPlus配置动态数据源

    目录 SpringBoot整合MyBatisPlus配置动态数据源 SpringBoot整合MyBatisPlus配置动态数据源 推文:2018开源中国最受欢迎的中国软件MyBatis-Plus My ...

  4. Spring3 整合MyBatis3 配置多数据源 动态选择SqlSessionFactory

    一.摘要 上两篇文章分别介绍了Spring3.3 整合 Hibernate3.MyBatis3.2 配置多数据源/动态切换数据源 方法 和 Spring3 整合Hibernate3.5 动态切换Ses ...

  5. Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源 方法

    一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...

  6. SpringBoot系列七:SpringBoot 整合 MyBatis(配置 druid 数据源、配置 MyBatis、事务控制、druid 监控)

    1.概念:SpringBoot 整合 MyBatis 2.背景 SpringBoot 得到最终效果是一个简化到极致的 WEB 开发,但是只要牵扯到 WEB 开发,就绝对不可能缺少数据层操作,所有的开发 ...

  7. Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源方法

    一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...

  8. mybatis-plus配置多数据源invalid bound statement (not found)

    mybatis-plus配置多数据源invalid bound statement (not found) 错误原因 引入mybatis-plus应该使用的依赖如下,而不是mybatis <de ...

  9. Spring Boot整合Druid配置多数据源

    Druid是阿里开发的数据库连接池,功能强大,号称Java语言中最好的数据库连接池.本文主要介绍Srping Boot下用Druid配置多个数据源,demo环境为:Spring Boot 2.1.4. ...

随机推荐

  1. 解决mysql java.sql.SQLException: The server time zone value‘XXXXXX' is unrecognized or represents...

    解决 java.sql.SQLException: The server time zone value 'XXXXXX' is unrecognized or represents more tha ...

  2. 转:OAuth2 深入介绍

    OAuth2 深入介绍 1. 前言 2. OAuth2 角色 2.1 资源所有者(Resource Owner) 2.2 资源/授权服务器(Resource/Authorization Server) ...

  3. MyBatis系列(一) MyBatis入门

    前言 MyBatis官方文档:https://mybatis.org/mybatis-3/zh/index.html MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由 ...

  4. CF1236B Alice and the List of Presents

    题意翻译 有nn种物品和mm个背包,每种物品有无限个,现将若干个物品放到这些背包中,满足: 1.每个背包里不能出现相同种类的物品(允许有空背包): 2.在所有的mm个背包中,每种物品都出现过. 求方案 ...

  5. ios 10 更新 新体验

    1.使用手机登录开发者网站https://developer.apple.com/download/ 2.下载描述文件 3.安装描述文件,按照提示步骤操作 4.更新ios系统 下面的方法是连接电脑直接 ...

  6. libcurl库浅析

    先放上libcurl官方文档:链接 第一步:全局初始化 #include <curl/curl.h> CURLcode curl_global_init(long flags ); 在使用 ...

  7. [TimLinux] JavaScript 引用类型——Date

    1. Date var now = new Date(); // 不传参数,获取当前日期.时间. now.getDay(); // 日期 now.getMonth(); // 月份 now.getFu ...

  8. 基于 asm 实现比 spring BeanUtils 性能更好的属性拷贝框架

    Bean-Mapping 日常开发中经常需要将一个对象的属性,赋值到另一个对象中. 常见的工具有很多,但都多少不够简洁,要么不够强大. 我们经常使用的 Spring BeanUtils 性能较好,但是 ...

  9. pipelineDB学习笔记-2. Stream (流)

    一.流的定义: 所谓的“流”(stream)在pipelineDB中是指那些被允许的数据库客服端推送到 Continuous View(连续视图) 的时序化数据的一种“抽象”.流中的每一个raw(数据 ...

  10. Rabbit安装(单机及集群,阿里云)

    Rabbit安装(单机及集群,阿里云) 前言 虽然我并不是部署人员,但是自己私人测试环境的各类东东还是得自己安装的. 尤其在规模不大的公司,基本安装部署工作都是后端的份内之事. 那么最令人痛苦的,莫过 ...