mysql通用mapper_spring boot整合mybatis通用mapper实现Druid多数据源

本文介绍了如何在Spring Boot项目中整合Mybatis通用Mapper和Druid,实现多数据源配置。通过配置多个数据源,并使用tk.mybatis.mapper的通用接口,简化了数据库操作。项目结构清晰,包括数据源配置类和对应的Mapper接口,展示了如何在Controller中调用不同数据源的Mapper方法获取数据。
摘要由CSDN通过智能技术生成

spring boot整合mybatis通用mapper实现Druid多数据源

发布时间:2018-05-18 11:00,

浏览次数:802

, 标签:

spring

boot

mybatis

mapper

Druid

在以前的项目中用springMVC加原生的mybatis框架使用过多数据源的配置,是用xml配置的。在这次的新项目里面使用到了tk的通用mapper,刚好项目结束,利用空闲时间写了个全注解的多数据源配置小demo。

现在互联网项目中流行使用Mybatis框架和Druid数据库连接池进行数据库的操作。本来直接是用的spring

boot整合mybatis做的多数据源,因为刚结束的项目中使用到了通用mapper这个免去sql编写,提高开发效率的组件,所以顺带的把这个组件也集成进来了。

因为主要讲的是多数据源的实现,对其他的框架组件就不花费太多的笔墨,以后会另外的花时间去记录。

首先看下项目的整体结构:

datasource包下面放的是数据源一和数据源二的配置

mapper包下面放的对应的mapper文件,注意

包要细分到不同的来源,比喻mapper.source1和mapper.source2,不同来源库的mapper文件要放到不同的source包下面。

项目是用maven工具构建的,肯定少不了在pom.xml文件里面添加相应的jar依赖:

<?xml version="1.0" encoding="UTF-8"?>

="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"

> 4.0.0com.lms

multiple-datasource 0.0.1-SNAPSHOT

jar multiple-datasourceDemo project

for Spring Boot org.springframework.boot

spring-boot-starter-parent

2.0.2.RELEASE

UTF-8

UTF-8

1.8

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-web

mysql mysql-connector-java

com.alibabadruid

1.1.8

org.springframework.boot spring-boot-starter-test

test

org.mybatis.spring.boot mybatis-spring-boot-starter

1.3.2

tk.mybatis

mapper-spring-boot-starter 1.2.4

org.springframework.boot

spring-boot-devtools true

org.springframework.boot

spring-boot-maven-plugin

添加完依赖之后就要开始配置数据库了,在application.properties文件里面配置数据库的地址和druid相关的一些配置:

mybatis.type-aliases-package=com.lms.multipledatasource.entity

spring.datasource.source1.driver-class-name= com.mysql.jdbc.Driver

spring.datasource.source1.url=

jdbc:mysql://192.168.2.115:3306/data_source_test1?useUnicode=true&characterEncoding=utf-8

spring.datasource.source1.username= root spring.datasource.source1.password =

8Nj1jo+I8f1qNQ#使用Druid数据源 spring.datasource.source1.initialSize=5 # 初始化大小,最小,最大

spring.datasource.source1.minIdle=5 spring.datasource.source1.maxActive= 20 #

配置获取连接等待超时的时间spring.datasource.source1.maxWait= 60000 #

配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒

spring.datasource.source1.timeBetweenEvictionRunsMillis= 60000 #

配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.source1.minEvictableIdleTimeMillis=

300000spring.datasource.source1.validationQuery= select 'x'

spring.datasource.source1.testWhileIdle= true

spring.datasource.source1.testOnBorrow= false

spring.datasource.source1.testOnReturn= false # 打开PSCache,并且指定每个连接上PSCache的大小

spring.datasource.source1.poolPreparedStatements= true

spring.datasource.source1.maxPoolPreparedStatementPerConnectionSize= 20 #

配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.source1.filters=

stat,wall,slf4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录

spring.datasource.source1.connectionProperties=

druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

spring.datasource.source2.driver-class-name= com.mysql.jdbc.Driver

spring.datasource.source2.url=

jdbc:mysql://192.168.2.115:3306/data_source_test2?useUnicode=true&characterEncoding=utf-8

spring.datasource.source2.username= root spring.datasource.source2.password =

8Nj1jo+I8f1qNQ#使用Druid数据源 spring.datasource.source2.initialSize=5 # 初始化大小,最小,最大

spring.datasource.source2.minIdle=5 spring.datasource.source2.maxActive= 20 #

配置获取连接等待超时的时间spring.datasource.source2.maxWait= 60000 #

配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒

spring.datasource.source2.timeBetweenEvictionRunsMillis= 60000 #

配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.source2.minEvictableIdleTimeMillis=

300000spring.datasource.source2.validationQuery= select 'x'

spring.datasource.source2.testWhileIdle= true

spring.datasource.source2.testOnBorrow= false

spring.datasource.source2.testOnReturn= false # 打开PSCache,并且指定每个连接上PSCache的大小

spring.datasource.source2.poolPreparedStatements= true

spring.datasource.source2.maxPoolPreparedStatementPerConnectionSize= 20 #

配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.source2.filters=

stat,wall,slf4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录

spring.datasource.source2.connectionProperties=

druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

mybatis.type-aliases-package配置可以自动的扫描mapper文件,但是需要在Mapper接口上标注@Mapper注解,下面配置了两个数据源source1和source2,如果还有更多的数据源,只需要依次的添加就可以了。

接下来创建两个数据源配置类DataSourceOneConfig和DataSourceTwoConfig

在配置数据源的时候,必要要配置一个主数据源,在这里把DataSourceOneConfig作为主数据源

@Configuration //扫描Mapper basePackages要精确到source1目录便于进行不同数据源的区分 @MapperScan(

basePackages= "com.lms.multipledatasource.mapper.source1", sqlSessionTemplateRef

="sqlSessionTemplateOne") public class DataSourceOneConfig { @Bean(name =

"dataSourceOne") @ConfigurationProperties(prefix = "spring.datasource.source1")

@Primary//设置主数据源 public DataSource DataSourceOne(){ DruidDataSource dataSource =

newDruidDataSource(); return dataSource; } @Bean public ServletRegistrationBean

druidStatViewServlet() { ServletRegistrationBean registrationBean = new

ServletRegistrationBean(new StatViewServlet(), "/druid/*");

registrationBean.addInitParameter("allow", "127.0.0.1"); // IP白名单

(没有配置或者为空,则允许所有访问) registrationBean.addInitParameter("deny", ""); // IP黑名单

(存在共同时,deny优先于allow) registrationBean.addInitParameter("loginUsername", "admin")

; registrationBean.addInitParameter("loginPassword", "admin");

registrationBean.addInitParameter("resetEnable", "false"); return

registrationBean; } @Bean public FilterRegistrationBean druidWebStatViewFilter

() { FilterRegistrationBean registrationBean =new FilterRegistrationBean(new

WebStatFilter()); registrationBean.addInitParameter("urlPatterns", "/*");

registrationBean.addInitParameter("exclusions",

"*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); return registrationBean;

}@Bean(name = "sqlSessionFactoryOne") @Primary public SqlSessionFactory

sqlSessionFactoryOne(@Qualifier("dataSourceOne") DataSource dataSource)throws

Exception{ SqlSessionFactoryBean bean =new SqlSessionFactoryBean();

bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name =

"dataSourceTransactionManagerOne") @Primary public DataSourceTransactionManager

dataSourceTransactionManagerOne(@Qualifier("dataSourceOne") DataSource

dataSource){return new DataSourceTransactionManager(dataSource); } @Bean(name =

"sqlSessionTemplateOne") @Primary public SqlSessionTemplate

sqlSessionTemplateOne(@Qualifier("sqlSessionFactoryOne") SqlSessionFactory

sqlSessionFactory)throws Exception{ return new

SqlSessionTemplate(sqlSessionFactory); } }

@Configuration 说明这是一个配置类

@MapperScan  扫描mapper接口和进行容器管理,注意的是basePackages要精确到source1目录便于和不同数据源的区分

@Primary 标志主数据源,一定要有且只能有一个主数据源,不然会报错的。

@ConfigurationProperties 读取properties配置文件里面的以spring.datasource.source1开头的数据库配置

在配置datasource的时候一定要用DruidDataSource类,不然的话druid数据库连接池是不会起作用的

public DataSource DataSourceOne(){ DruidDataSource dataSource = new

DruidDataSource(); return dataSource; }

druidStatViewServlet()和druidWebStatViewFilter()是配置durid的登陆地址和登陆账户的。

同理DataSourceTwoConfig类中的配置和DataSourceOneConfig里面的是差不多的

,把source1改为source2即可,并且不需要@Primary注解

@Configuration @MapperScan(basePackages =

"com.lms.multipledatasource.mapper.source2", sqlSessionTemplateRef =

"sqlSessionTemplateTwo") public class DataSourceTwoConfig { @Bean(name =

"dataSourceTwo") @ConfigurationProperties(prefix = "spring.datasource.source2")

publicDataSource DataSourceOne(){ DruidDataSource dataSource = new

DruidDataSource(); return dataSource; } @Bean public ServletRegistrationBean

druidStatViewServlet() { ServletRegistrationBean registrationBean = new

ServletRegistrationBean(new StatViewServlet(), "/druid/*");

registrationBean.addInitParameter("allow", "127.0.0.1"); // IP白名单

(没有配置或者为空,则允许所有访问) registrationBean.addInitParameter("deny", ""); // IP黑名单

(存在共同时,deny优先于allow) registrationBean.addInitParameter("loginUsername", "admin")

; registrationBean.addInitParameter("loginPassword", "admin");

registrationBean.addInitParameter("resetEnable", "false"); return

registrationBean; } @Bean public FilterRegistrationBean druidWebStatViewFilter

() { FilterRegistrationBean registrationBean =new FilterRegistrationBean(new

WebStatFilter()); registrationBean.addInitParameter("urlPatterns", "/*");

registrationBean.addInitParameter("exclusions",

"*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); return registrationBean;

}@Bean(name = "sqlSessionFactoryTwo") public SqlSessionFactory

sqlSessionFactoryOne(@Qualifier("dataSourceTwo") DataSource dataSource)throws

Exception{ SqlSessionFactoryBean bean =new SqlSessionFactoryBean();

bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name =

"dataSourceTransactionManagerTwo") public DataSourceTransactionManager

dataSourceTransactionManagerOne(@Qualifier("dataSourceTwo") DataSource

dataSource){return new DataSourceTransactionManager(dataSource); } @Bean(name =

"sqlSessionTemplateTwo") public SqlSessionTemplate sqlSessionTemplateOne(

@Qualifier("sqlSessionFactoryTwo") SqlSessionFactory sqlSessionFactory)throws

Exception{return new SqlSessionTemplate(sqlSessionFactory); }

到这里,基本的数据源配置就已经差不多结束了,接下来的service,mapper,conttroller就和平常写项目是一样的,没有什么太大的区别。

因为使用的是tk通用mapper,所以我们在自己定义一个接口去是继承tk的两个接口Mapper, MySqlMapper

,自己定义的接口名称可以随自己定,和普通的接口一样,没有特殊的要求。在这里取名为CommnMapper,注意的是一定要带上泛型。这个接口上面不需要任何的注解

public interface CommnMapper extends Mapper, MySqlMapper { }

然后新建一个UserInfoOneMapper接口继承刚刚创建的CommnMapper接口,接口上面要添加@Component和@Mapper来说明这个接口是一个组件和一个mapper文件

@Component @Mapper public interface UserInfoOneMapper extends

CommnMapper{ }

这个mapper连接的是userinfo表,所以泛型里面用的是UserInfoEntity对象。mapper连接的是哪个表,泛型里面对应的就是哪个表对应的实体类对象。

@Component @Table(name = "userinfo") public class UserInfoEntity { @Id private

Integerid; private String userName; private String departName; private Date

created;

@Table里面name的值是数据库里面对应的表名,一定不要填错了。

然后我们就可以在service里面调用mapper的增删查改方法来对表里面的数据进行对应的操作了。因为这只是一个demo,所以就没有创建service层,直接在controller实例化了mapper调用了对应的方法

@RestController public class UserInfoController { @Autowired private

UserInfoOneMapperuserInfoOneMapper; @Autowired private UserInfoTwoMapper

userInfoTwoMapper; @RequestMapping("/getOneUserById") public UserInfoEntity

getOneUserById(Integer id){ UserInfoEntity entity = new UserInfoEntity();

entity.setId(id); UserInfoEntity entity1 = userInfoOneMapper.selectOne(entity);

returnentity1; } @RequestMapping("/getAllUserForOne") public

ListgetAllUserForOne(){ List allUser =

userInfoOneMapper.selectAll(); return allUser; } @RequestMapping(

"/getTwoUserById") public UserInfoEntity getTwoUserById(Integer id){

UserInfoEntity entity =new UserInfoEntity(); entity.setId(id); UserInfoEntity

entity1 =userInfoTwoMapper.selectOne(entity); return entity1; } @RequestMapping

("/getAllUserForTwo") public List getAllUserForTwo(){

List allUser =userInfoTwoMapper.selectAll(); return allUser; }

}

启动项目,在postman里面调用不同的接口,可以获取到不同的表里面的数据。

调用getOneUserById,传id=1获得返回数据:

调用getTwoUserById,传id=1获得返回数据:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值