SpringBoot+Mybatis+ Druid+PageHelper implements multiple data sources and paging

foreword

This article mainly talks about SpringBoot integrating Mybatis , Druid and PageHelper and implementing multiple data sources and paging. Among them, SpringBoot integrates Mybatis, which has been described in a previous article , so I won't explain it too much here. The focus is on how to configure and use Druid and PageHelper under multiple data sources.

Druid introduction and use

Before using Druid , let's briefly understand Druid.

Druid is a database connection pool. Druid can be said to be the best database connection pool at present! It is favored by developers for its excellent functionality, performance and scalability.
Druid has deployed more than 600 applications in Alibaba, and has undergone a rigorous test of large-scale deployment in production environments for more than a year. Druid is a database connection pool developed by Alibaba called monitoring!

At the same time, Druid is not just a database connection pool. The core of Druid mainly includes three parts:

  • Plug-in system based on Filter-Chain mode.
  • DruidDataSource Efficient and manageable database connection pool.
  • SQLParser

The main functions of Druid are as follows:

  1. It is an efficient, powerful and scalable database connection pool.
  2. Database access performance can be monitored.
  3. Database password encryption
  4. Get SQL execution log
  5. Extended JDBC

In terms of introduction, I won't say more about it. For details, please refer to the official documentation.
Then start to introduce how Druid is used.

The first is the Maven dependency, just add the druid jar.

<dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>druid</artifactId>
         <version>1.1.8</version>
  </dependency>

In terms of configuration, the main thing is to add the following in application.properties or application.yml .
Description: Because I am using two data sources here, it is slightly different. The description of Druid configuration has been described in detail below, so I will not explain it here.

## 默认的数据源

master.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
master.datasource.username=root
master.datasource.password=123456
master.datasource.driverClassName=com.mysql.jdbc.Driver


## 另一个的数据源
cluster.datasource.url=jdbc:mysql://localhost:3306/springBoot_test?useUnicode=true&characterEncoding=utf8
cluster.datasource.username=root
cluster.datasource.password=123456
cluster.datasource.driverClassName=com.mysql.jdbc.Driver

# 连接池的配置信息  
# 初始化大小,最小,最大  
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  
# 配置获取连接等待超时的时间  
spring.datasource.maxWait=60000  
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒  
spring.datasource.timeBetweenEvictionRunsMillis=60000  
# 配置一个连接在池中最小生存的时间,单位是毫秒  
spring.datasource.minEvictableIdleTimeMillis=300000  
spring.datasource.validationQuery=SELECT 1 FROM DUAL  
spring.datasource.testWhileIdle=true  
spring.datasource.testOnBorrow=false  
spring.datasource.testOnReturn=false  
# 打开PSCache,并且指定每个连接上PSCache的大小  
spring.datasource.poolPreparedStatements=true  
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙  
spring.datasource.filters=stat,wall,log4j  
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录  
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000  

After successfully adding the configuration file, let's write Druid-related classes.
The first is the MasterDataSourceConfig.java class, which is the default data source configuration class.

@Configuration
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {

    static final String PACKAGE = "com.pancm.dao.master";
    static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";

    @Value("${master.datasource.url}")  
    private String url;  
      
    @Value("${master.datasource.username}")  
    private String username;  
      
    @Value("${master.datasource.password}")  
    private String password;  
      
    @Value("${master.datasource.driverClassName}")  
    private String driverClassName;  
      
    
    
    
    @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.validationQuery}")  
    private String validationQuery;  
      
    @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;  
      
    @Value("${spring.datasource.filters}")  
    private String filters;  
      
    @Value("{spring.datasource.connectionProperties}")  
    private String connectionProperties;  
    
    
    @Bean(name = "masterDataSource")
    @Primary 
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);  
        dataSource.setUsername(username);  
        dataSource.setPassword(password);  
        dataSource.setDriverClassName(driverClassName);  
          
        //具体配置 
        dataSource.setInitialSize(initialSize);  
        dataSource.setMinIdle(minIdle);  
        dataSource.setMaxActive(maxActive);  
        dataSource.setMaxWait(maxWait);  
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        dataSource.setValidationQuery(validationQuery);  
        dataSource.setTestWhileIdle(testWhileIdle);  
        dataSource.setTestOnBorrow(testOnBorrow);  
        dataSource.setTestOnReturn(testOnReturn);  
        dataSource.setPoolPreparedStatements(poolPreparedStatements);  
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);  
        try {  
            dataSource.setFilters(filters);  
        } catch (SQLException e) { 
            e.printStackTrace();
        }  
        dataSource.setConnectionProperties(connectionProperties);  
        return dataSource;
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MasterDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

These two annotations describe:

  • **@Primary* * : Mark this bean If there are multiple candidates of the same type of bean, the bean will
    be considered first. When configuring multiple data sources, note that there must be a primary data source, and mark the bean with @Primary.

  • **@MapperScan** : Scan Mapper interface and container management.

It should be noted that sqlSessionFactoryRef represents the definition of a unique SqlSessionFactory instance.

After the above configuration is complete, Druid can be used as a connection pool. But Druid is not simply a connection pool, it can also be said to be a monitoring application, it comes with a web monitoring interface, you can clearly see SQL-related information. To use Druid 's monitoring function
in SpringBoot , you only need to write StatViewServlet and WebStatFilter classes to implement registration services and filtering rules. Here we can write these two together, using **@Configuration** and **@Bean** . For the convenience of understanding, the relevant configuration instructions are also written in the code, so I won't repeat them here. code show as below:

@Configuration
public class DruidConfiguration {

    @Bean
    public ServletRegistrationBean druidStatViewServle() {
        //注册服务
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
                new StatViewServlet(), "/druid/*");
        // 白名单(为空表示,所有的都可以访问,多个IP的时候用逗号隔开)
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // IP黑名单 (存在共同时,deny优先于allow) 
        servletRegistrationBean.addInitParameter("deny", "127.0.0.2");
        // 设置登录的用户名和密码
        servletRegistrationBean.addInitParameter("loginUsername", "pancm");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        // 是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean druidStatFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(
                new WebStatFilter());
        // 添加过滤规则
        filterRegistrationBean.addUrlPatterns("/*");
        // 添加不需要忽略的格式信息
        filterRegistrationBean.addInitParameter("exclusions",
                "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        System.out.println("druid初始化成功!");
        return filterRegistrationBean;

    }
}

After writing, start the program, enter: http://127.0.0.1:8084/druid/index.html in the browser , and then enter the set user name and password to access the web interface.

Multiple data source configuration

Before configuring multiple data sources , execute the following scripts in the mysql databases of springBoot and springBoot_test respectively.

-- springBoot库的脚本

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',
  `name` varchar(10) DEFAULT NULL COMMENT '姓名',
  `age` int(2) DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8

-- springBoot_test库的脚本

CREATE TABLE `t_student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(16) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

Note: In order to be lazy, the structures of the two tables are made the same! But it doesn't affect the test!

The information of these two data sources has been configured in application.properties , and the configuration has been posted once, so it will not be posted here.
Here we focus on the configuration of the second data source. Similar to the above MasterDataSourceConfig.java , the difference is that the **@Primary* * annotation and name are not used. It should be noted that MasterDataSourceConfig.java scans the package and mapper accurately to the directory, and the same is true for the second data source here. Then the code is as follows:

@Configuration
@MapperScan(basePackages = ClusterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "clusterSqlSessionFactory")
public class ClusterDataSourceConfig {

 static final String PACKAGE = "com.pancm.dao.cluster";
 static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml";

 @Value("${cluster.datasource.url}")
 private String url;

 @Value("${cluster.datasource.username}")
 private String username;

 @Value("${cluster.datasource.password}")
 private String password;

 @Value("${cluster.datasource.driverClassName}")
 private String driverClass;

 // 和MasterDataSourceConfig一样,这里略

 @Bean(name = "clusterDataSource")
 public DataSource clusterDataSource() {
     DruidDataSource dataSource = new DruidDataSource();
     dataSource.setUrl(url);  
     dataSource.setUsername(username);  
     dataSource.setPassword(password);  
     dataSource.setDriverClassName(driverClass);  
   
     // 和MasterDataSourceConfig一样,这里略 ...
     return dataSource;
 }

 @Bean(name = "clusterTransactionManager")
 public DataSourceTransactionManager clusterTransactionManager() {
     return new DataSourceTransactionManager(clusterDataSource());
 }

 @Bean(name = "clusterSqlSessionFactory")
 public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
         throws Exception {
     final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
     sessionFactory.setDataSource(clusterDataSource);
     sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(ClusterDataSourceConfig.MAPPER_LOCATION));
     return sessionFactory.getObject();
 }
}

After successfully writing the configuration, start the program and test it. Use interfaces to add data in the springBoot and springBoot_test
libraries, respectively .

t_user

POST http://localhost:8084/api/user
{"name":"张三","age":25}
{"name":"李四","age":25}
{"name":"王五","age":25}

t_student

POST http://localhost:8084/api/student
{"name":"学生A","age":16}
{"name":"学生B","age":17}
{"name":"学生C","age":18}

After successfully adding data, call different interfaces for query.

ask:

GET http://localhost:8084/api/user?name=李四

return:

{
    "id": 2,
    "name": "李四",
    "age": 25
}

ask:

 GET http://localhost:8084/api/student?name=学生C

return:

{
    "id": 1,
    "name": "学生C",
    "age": 16
}

It can be seen from the data that multiple data sources have been successfully configured.

PageHelper paging implementation

PageHelper is a paging plugin for Mybatis, very easy to use! Highly recommended here! ! !

The use of PageHelper is very simple, just add the pagehelper dependency in Maven.
Maven's dependencies are as follows:

   <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

Note: I use the springBoot version here! Other versions can also be used.

After adding dependencies, you only need to add the following configuration or code.
The first, add in application.properties or application.yml

  pagehelper:
  helperDialect: mysql
  offsetAsPageNum: true
  rowBoundsWithCount: true
  reasonable: false

The second, add in the mybatis.xml configuration

  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!-- 扫描mapping.xml文件 -->
    <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    <!-- 配置分页插件 -->
     <property name="plugins">
        <array>
          <bean class="com.github.pagehelper.PageHelper">
            <property name="properties">
              <value>
                helperDialect=mysql
                offsetAsPageNum=true
                rowBoundsWithCount=true
                reasonable=false
              </value>
            </property>
          </bean>
        </array>
      </property>
  </bean>

The third is to add it in the code and use the **@Bean** annotation to initialize when the program is started .

 @Bean
  public PageHelper pageHelper(){
    PageHelper pageHelper = new PageHelper();
   Properties properties = new Properties();
   //数据库
   properties.setProperty("helperDialect", "mysql");
   //是否将参数offset作为PageNum使用
   properties.setProperty("offsetAsPageNum", "true");
   //是否进行count查询
   properties.setProperty("rowBoundsWithCount", "true");
   //是否分页合理化
   properties.setProperty("reasonable", "false");
   pageHelper.setProperties(properties);
  }

Because here we are using multiple data sources, the configuration here is slightly different. We need to configure sessionFactory here. Here, make corresponding modifications to MasterDataSourceConfig.java . In the masterSqlSessionFactory method, add the following code.

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MasterDataSourceConfig.MAPPER_LOCATION));
        //分页插件
        Interceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        //数据库
        properties.setProperty("helperDialect", "mysql");
        //是否将参数offset作为PageNum使用
        properties.setProperty("offsetAsPageNum", "true");
        //是否进行count查询
        properties.setProperty("rowBoundsWithCount", "true");
        //是否分页合理化
        properties.setProperty("reasonable", "false");
        interceptor.setProperties(properties);
        sessionFactory.setPlugins(new Interceptor[] {interceptor});
        
    return sessionFactory.getObject();
  }

Note: When other data sources also want to perform paging, please refer to the above code.

It should be noted here that the reasonable parameter indicates paging rationalization, and the default value is false. If this parameter is set to true, the first page will be queried when pageNum<=0, and the last page will be queried when pageNum>pages (when it exceeds the total number). When the default is false, the query is performed directly according to the parameters.

After setting PageHelper, if you want to use it, you only need to add PageHelper.startPage(pageNum,pageSize); in front of the query sql , if you want to know the total number, just add page.getTotal() after the query sql statement .
Code example:

public List<T> findByListEntity(T entity) {
        List<T> list = null;
        try {
            Page<?> page =PageHelper.startPage(1,2); 
            System.out.println(getClassName(entity)+"设置第一页两条数据!");
            list = getMapper().findByListEntity(entity);
            System.out.println("总共有:"+page.getTotal()+"条数据,实际返回:"+list.size()+"两条数据!");
        } catch (Exception e) {
            logger.error("查询"+getClassName(entity)+"失败!原因是:",e);
        }
        return list;
    }

After the code is written, the final test begins.

Query all the data in the t_user table and perform pagination.

ask:

GET http://localhost:8084/api/user

return:

[
    {
        "id": 1,
        "name": "张三",
        "age": 25
    },
    {
        "id": 2,
        "name": "李四",
        "age": 25
    }
]

console print:

开始查询...
User设置第一页两条数据!
2018-04-27 19:55:50.769 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT   : ==>  Preparing: SELECT count(0) FROM t_user WHERE 1 = 1 
2018-04-27 19:55:50.770 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT   : ==> Parameters: 
2018-04-27 19:55:50.771 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT   : <==      Total: 1
2018-04-27 19:55:50.772 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity  : ==>  Preparing: select id, name, age from t_user where 1=1 LIMIT ? 
2018-04-27 19:55:50.773 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity  : ==> Parameters: 2(Integer)
2018-04-27 19:55:50.774 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity  : <==      Total: 2
总共有:3条数据,实际返回:2两条数据!

Query all the data in the t_student table and perform pagination.

ask:

GET  http://localhost:8084/api/student

return:

[
    {
        "id": 1,
        "name": "学生A",
        "age": 16
    },
    {
        "id": 2,
        "name": "学生B",
        "age": 17
    }
]

console print:

开始查询...
Studnet设置第一页两条数据!
2018-04-27 19:54:56.155 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT         : ==>  Preparing: SELECT count(0) FROM t_student WHERE 1 = 1 
2018-04-27 19:54:56.155 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT         : ==> Parameters: 
2018-04-27 19:54:56.156 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT         : <==      Total: 1
2018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity      : ==>  Preparing: select id, name, age from t_student where 1=1 LIMIT ? 
2018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity      : ==> Parameters: 2(Integer)
2018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity      : <==      Total: 2
总共有:3条数据,实际返回:2两条数据!

After the query is complete, let's look at Druid's monitoring interface. Type in the browser: http://127.0.0.1:8084/druid/index.html

You can clearly see the operation records!
If you want to know more about Druid, you can check the official documentation!

Epilogue

This article is finally finished. When writing the code, I encountered many problems, and then slowly tried and found information to solve it. This article only briefly introduces these related uses, and the actual application may be more complicated. If you have better ideas and suggestions, please leave a message for discussion!

Reference article: https://www.bysocket.com/?p=1712

Durid official address: https://github.com/alibaba/druid

PageHelper official address: https://github.com/pagehelper/Mybatis-PageHelper

I put the project on github:
https://github.com/xuwujing/springBoot

If it feels good, I hope to give a star by the way.
This is the end of this article, thank you for reading.

Copyright statement:
Author: Nothingness
Blog Garden Source: http://www.cnblogs.com/xuwujing
CSDN Source: http://blog.csdn.net/qazwsxpcm    
Personal Blog Source: http://www.panchengming.com
Original It's not easy, please indicate the source when reprinting, thank you!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324989752&siteId=291194637