springboot + 多数据源mysql、oracle + pagehelper 分页

springboot + 多数据源mysql、oracle + pagehelper 分页
项目使用maven依赖

1 配置多数据源,以及多数据源分页,导包



      mysql
       mysql-connector-java



    com.oracle
     ojdbc6
     11.2.0.3
 
 

	com.github.pagehelper
	pagehelper
	${pagehelper.version}

2 yml或propertites配置文件

spring:
  datasource-sysadm:
    driverClassName: oracle.jdbc.driver.OracleDriver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:oracle:thin:@ip:prot:服务名或sid
    username: 用户名
    password: 密码
    # 查询时进行校验
    validationQuery: select 1 from dual
  datasource:
    driverClassName : com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://ip:port/数据库名称?useUnicode=true&useSSL=false&characterEncoding=utf8&characterSetResults=utf8
    username: 用户名
    password :密码
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
    initialSize: 10
    minIdle: 30
    maxActive: 100
# 配置获取连接等待超时的时间
    maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1
    testWhileIdle: true
    testOnBorrow: false
    exceptionSorter: true
    testOnReturn: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20

3 配置数据源

3.1 多数据源必须有一个主数据源,默认mysql为主数据源,添加配置文件
package com.XXX.bpaas.idm.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;


@Configuration
@MapperScan(basePackages="com.XXX.bpaas.idm.mapper.dao", sqlSessionTemplateRef = "idmSqlSessionTemplate") //扫描到具体的包
public class IdmDataSourceConfig {
	//日志
	private Logger log = LoggerFactory.getLogger(IdmDataSourceConfig.class);
	
	//精确到 具体 目录,以便跟其他数据源隔离
	private static final String MAPPER_LOCATION = "classpath:mybatis/mapper/*.xml";
	
	@Value("${spring.datasource.url}")
	private String dbUrl;
	@Value("${spring.datasource.type}")
	private String dbtype;
	@Value("${spring.datasource.username}")
	private String username;
	@Value("${spring.datasource.password}")
	private String password;
	@Value("${spring.datasource.driverClassName}")
	private String driverClassName;
	@Value("${spring.datasource.validationQuery}")
	private String validationQuery;
	//以下的配置从配置文件中读取
	@Value("${spring.datasource.initialSize}")
	private int initialSize;
	@Value("${spring.datasource.minIdle}")
	private int minIdle;
	@Value("${spring.datasource.maxActive}")
	private int maxActive;
	@Value("${spring.datasource.maxWait}")
	private int maxWait;
	@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
	private int timeBetweenEvictionRunsMillis;
	@Value("${spring.datasource.minEvictableIdleTimeMillis}")
	private int minEvictableIdleTimeMillis;
	@Value("${spring.datasource.testWhileIdle}")
	private boolean testWhileIdle;
	@Value("${spring.datasource.testOnBorrow}")
	private boolean testOnBorrow;
	@Value("${spring.datasource.testOnReturn}")
	private boolean testOnReturn;
	@Value("${spring.datasource.poolPreparedStatements}")
	private boolean poolPreparedStatements;
	@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
	private int maxPoolPreparedStatementPerConnectionSize;

	/**
	 * 设置主数据源的参数
	 */
	@Bean
	@Primary
	public DruidDataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(this.dbUrl);
		datasource.setDbType(dbtype);
		datasource.setUsername(this.username);
		datasource.setPassword(this.password);
		datasource.setDriverClassName(this.driverClassName);
		datasource.setInitialSize(this.initialSize);
		datasource.setMinIdle(this.minIdle);
		datasource.setMaxActive(this.maxActive);
		datasource.setMaxWait((long) this.maxWait);
		datasource.setTimeBetweenEvictionRunsMillis((long) this.timeBetweenEvictionRunsMillis);
		datasource.setMinEvictableIdleTimeMillis((long) this.minEvictableIdleTimeMillis);
		datasource.setValidationQuery(this.validationQuery);
		datasource.setTestWhileIdle(this.testWhileIdle);
		datasource.setTestOnBorrow(this.testOnBorrow);
		datasource.setTestOnReturn(this.testOnReturn);
		datasource.setPoolPreparedStatements(this.poolPreparedStatements);
		datasource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize);
		return datasource;
	}
	
	/**
	 * 设置数据源的事务
	 */
	@Bean(name = "idmTransactionManager")
	@Primary
	public DataSourceTransactionManager idmTransactionManager() {
		log.info("---------idmTransactionManager-------" + "加载完成");
		return new DataSourceTransactionManager(dataSource());
	}
	
	/**
	 * 连接池管道
	 */
	@Bean(name = "idmSqlSessionFactory")
	@Primary
	public SqlSessionFactory idmSqlSessionFactory(@Qualifier("dataSource") DataSource idmDataSource)
			throws Exception {
		log.info("--------clusterSqlSessionFactory-------" + "加载完成");
		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(idmDataSource);
		sessionFactory.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources(IdmDataSourceConfig.MAPPER_LOCATION));
		
		
		return sessionFactory.getObject();
	}
	
	/**
	 * 数据sql模板
	 */
	@Bean(name = "idmSqlSessionTemplate")
	@Primary
	public SqlSessionTemplate kdysSqlSessionTemplate(
			@Qualifier("idmSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

3.2 配置从数据源,oracle
package com.XXX.bpaas.idm.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;


@Configuration
@MapperScan(basePackages="com.XXX.bpaas.sysadm.mapper.dao", sqlSessionTemplateRef = "sysadmSqlSessionTemplate") //扫描到具体的包
public class SysadmDataSourceConfig {
	//日志
	private Logger log = LoggerFactory.getLogger(SysadmDataSourceConfig.class);
	
	//精确到 具体 目录,以便跟其他数据源隔离
	private static final String MAPPER_LOCATION = "classpath:mybatis/mapper-sysadm/*.xml";
	
	@Value("${spring.datasource-sysadm.url}")
	private String dbUrl;
	@Value("${spring.datasource-sysadm.type}")
	private String dbtype;
	@Value("${spring.datasource-sysadm.username}")
	private String username;
	@Value("${spring.datasource-sysadm.password}")
	private String password;
	@Value("${spring.datasource-sysadm.driverClassName}")
	private String driverClassName;
	@Value("${spring.datasource-sysadm.validationQuery}")
	private String validationQuery;
	//以下的配置从配置文件中读取
	@Value("${spring.datasource.initialSize}")
	private int initialSize;
	@Value("${spring.datasource.minIdle}")
	private int minIdle;
	@Value("${spring.datasource.maxActive}")
	private int maxActive;
	@Value("${spring.datasource.maxWait}")
	private int maxWait;
	@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
	private int timeBetweenEvictionRunsMillis;
	@Value("${spring.datasource.minEvictableIdleTimeMillis}")
	private int minEvictableIdleTimeMillis;
	@Value("${spring.datasource.testWhileIdle}")
	private boolean testWhileIdle;
	@Value("${spring.datasource.testOnBorrow}")
	private boolean testOnBorrow;
	@Value("${spring.datasource.testOnReturn}")
	private boolean testOnReturn;
	@Value("${spring.datasource.poolPreparedStatements}")
	private boolean poolPreparedStatements;
	@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
	private int maxPoolPreparedStatementPerConnectionSize;
	
	
	/**
	 * 设置主数据源的参数
	 */
	@Bean(name="sysadmDataSource")
	public DruidDataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(this.dbUrl);
		datasource.setDbType(this.dbtype);
		datasource.setUsername(this.username);
		datasource.setPassword(this.password);
		datasource.setDriverClassName(this.driverClassName);
		datasource.setInitialSize(this.initialSize);
		datasource.setMinIdle(this.minIdle);
		datasource.setMaxActive(this.maxActive);
		datasource.setMaxWait((long) this.maxWait);
		datasource.setTimeBetweenEvictionRunsMillis((long) this.timeBetweenEvictionRunsMillis);
		datasource.setMinEvictableIdleTimeMillis((long) this.minEvictableIdleTimeMillis);
		datasource.setValidationQuery(this.validationQuery);
		datasource.setTestWhileIdle(this.testWhileIdle);
		datasource.setTestOnBorrow(this.testOnBorrow);
		datasource.setTestOnReturn(this.testOnReturn);
		datasource.setPoolPreparedStatements(this.poolPreparedStatements);
		datasource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize);
		return datasource;
	}
	
	/**
	 * 设置数据源的事务
	 */
	@Bean(name = "sysadmTransactionManager")
	public DataSourceTransactionManager idmTransactionManager() {
		log.info("---------sysadmTransactionManager-------" + "加载完成");
		return new DataSourceTransactionManager(dataSource());
	}
	
	/**
	 * 连接池管道
	 */
	@Bean(name = "sysadmSqlSessionFactory")
	public SqlSessionFactory sysadmSqlSessionFactory(@Qualifier("sysadmDataSource") DataSource sysadmDataSource)
			throws Exception {
		log.info("--------sysadmSqlSessionFactory-------" + "加载完成");
		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(sysadmDataSource);
		sessionFactory.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources(SysadmDataSourceConfig.MAPPER_LOCATION));
		
		
		return sessionFactory.getObject();
	}
	
	@Bean(name = "sysadmSqlSessionTemplate")
	public SqlSessionTemplate kdysSqlSessionTemplate(
			@Qualifier("sysadmSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

以上多数据源即可使用了,如果需要其他数据源,继续添加即可

4 本demo使用pagehelper作为分页插件

4.1如果使用单数据源,可在配置文件中配置如下:
pagehelper:
  helperDialect: mysql
  reasonable: false
  supportMethodsArguments: true
  params: count=countSql
 

pagehelper 官网的连接
(1) helperDialect:分页插件会自动检测当前的数据库链接,自动选择合适的分页方式。 你可以配置helperDialect属性来指定分页插件使用哪种方言。配置时,可以使用下面的缩写值:
oracle,mysql,mariadb,sqlite,hsqldb,postgresql,db2,sqlserver,informix,h2,sqlserver2012,derby
特别注意:使用 SqlServer2012 数据库时,需要手动指定为 sqlserver2012,否则会使用 SqlServer2005 的方式进行分页。
你也可以实现 AbstractHelperDialect,然后配置该属性为实现类的全限定名称即可使用自定义的实现方法。

(2) offsetAsPageNum:默认值为 false,该参数对使用 RowBounds 作为分页参数时有效。 当该参数设置为 true 时,会将 RowBounds 中的 offset 参数当成 pageNum 使用,可以用页码和页面大小两个参数进行分页。

(3) rowBoundsWithCount:默认值为false,该参数对使用 RowBounds 作为分页参数时有效。 当该参数设置为true时,使用 RowBounds 分页会进行 count 查询。

(4) pageSizeZero:默认值为 false,当该参数设置为 true 时,如果 pageSize=0 或者 RowBounds.limit = 0 就会查询出全部的结果(相当于没有执行分页查询,但是返回结果仍然是 Page 类型)。

(5) reasonable:分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页。默认false 时,直接根据参数进行查询。

(6) params:为了支持startPage(Object params)方法,增加了该参数来配置参数映射,用于从对象中根据属性名取值, 可以配置 pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值, 默认值为pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero。

(7) supportMethodsArguments:支持通过 Mapper 接口参数来传递分页参数,默认值false,分页插件会从查询方法的参数值中,自动根据上面 params 配置的字段中取值,查找到合适的值时就会自动分页。 使用方法可以参考测试代码中的 com.github.pagehelper.test.basic 包下的 ArgumentsMapTest 和 ArgumentsObjTest。

(8) autoRuntimeDialect:默认值为 false。设置为 true 时,允许在运行时根据多数据源自动识别对应方言的分页 (不支持自动选择sqlserver2012,只能使用sqlserver)

4.2 如果使用多数据源,需要修改pagehelper配置项,配置如下
pagehelper:
#  helperDialect: mysql
  reasonable: false
  supportMethodsArguments: true
  params: count=countSql
# 默认false,当为true时,自动检验适合的数据库
  auto-dialect: true
   # 这个一定要加上,不然mysql和oracle分页两个只能用一个,另一个会报错,加上后,两中数据库分页都可以用了
  auto-runtime-dialect: true

如来神掌,写完收工

你可能感兴趣的:(springboot + 多数据源mysql、oracle + pagehelper 分页)