zoukankan      html  css  js  c++  java
  • SpringBoot2.0之五 优雅整合SpringBoot2.0+MyBatis+druid+PageHelper

         上篇文章我们介绍了SpringBoot和MyBatis的整合,可以说非常简单快捷的就搭建了一个web项目,但是在一个真正的企业级项目中,可能我们还需要更多的更加完善的框架才能开始真正的开发,比如连接池、分页插件等。下面我们就来看看在SpringBoot中怎么快速的集成这些东西。

    一、新建一个项目,引入相关依赖,加粗的是本项目中新引入的依赖

       <!-- 单元测试依赖 start -->
      <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
        <!-- 单元测试依赖 end -->
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.1</version>
        </dependency>
        
        <!-- 数据库连接池 start -->
        <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>druid</artifactId>
           <version>1.1.8</version>
       </dependency>
       <!-- 数据库连接池 end -->
        
        <!-- mysql连接 start -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- mysql连接 end -->
        
        <!-- pagehelper分页 start -->
        <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
       </dependency>

       <!-- pagehelper分页 start -->

    二、为了项目配置的整洁性,在SpringBoot-mybatis的项目基础上,我将数据库和MyBatis的相关操作进行了统一配置,使得配置根据清晰简单,项目结构如下

    后期项目会将所有的配置放在configuration包下,具体数据库配置如下

    @Configuration
    @MapperScan(value = "com.somta.springboot.dao")
    public class MyBatisConfiguration {

        @Value("${spring.datasource.driver-class-name}")
        private String driverClassName;

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

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

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

        @Bean
        public DruidDataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(this.driverClassName);
            dataSource.setUrl(this.url);
            dataSource.setUsername(this.username);
            dataSource.setPassword(this.password);

            dataSource.setInitialSize(5);
            dataSource.setMaxActive(30);
            dataSource.setMinIdle(5);
            dataSource.setMaxWait(60000);
            return dataSource;
        }

        @Bean(name="sqlSessionFactory")
        public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSource);
            sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
            sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/**/Mysql_*Mapper.xml"));
            return sqlSessionFactoryBean;
        }
    }

    1、将Dao层扫描和MyBatis文件的扫描统一放在配置文件中,如上文中的加粗项

    2、使用了阿里开源的Druid连接池,SpringBoot默认使用的连接池是Hikari,两者之间的优缺点后续将会单独介绍,配置成功后启动项目,我们可以看到项目当前使用的是那种连接池,如下图:

    3、在src/main/resources下面新增了一个mybatis-config文件,该文件配置了MyBatis与数据库的相关信息,和PageHelper的相关配置,注意:(在不同的PageHelper版本中PageHelper的拦截器发生了变化,PageHelper-4.1.1中使用的是com.github.pagehelper.PageHelper,在PageHelper-5.1.2中使用的拦截器是com.github.pagehelper.PageInterceptor,具体小版本以官网公告为准)

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <properties>
            <property name="dialect" value="mysql"/>
        </properties>
        <settings>
            <!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true -->
            <setting name="cacheEnabled" value="true"/>
            <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true -->
            <setting name="lazyLoadingEnabled" value="true"/>
            <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true -->
            <setting name="multipleResultSetsEnabled" value="true"/>
            <!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true -->
            <setting name="useColumnLabel" value="true"/>
            <!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如
                Derby)。 系统默认值是false -->
            <setting name="useGeneratedKeys" value="false"/>
            <!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE -->
            <setting name="defaultExecutorType" value="SIMPLE"/>
            <!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null -->
            <setting name="defaultStatementTimeout" value="25000"/>
            <!--设置字段和类是否支持驼峰命名的属性。 系统默认值是false -->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <!-- 打印查询语句 -->  
            <!-- <setting name="logImpl" value="STDOUT_LOGGING" /> -->  
        </settings>
        <plugins>
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!-- 该参数默认为false -->
                <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
                <!-- 和startPage中的pageNum效果一样-->
                <property name="offsetAsPageNum" value="true"/>
                <!-- 该参数默认为false -->
                <!-- 设置为true时,使用RowBounds分页会进行count查询 -->
                <property name="rowBoundsWithCount" value="true"/>
                <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
                <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->
                <property name="pageSizeZero" value="true"/>
                <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
                <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
                <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
                <property name="reasonable" value="false"/>
                <!-- 支持通过Mapper接口参数来传递分页参数 -->
                <property name="supportMethodsArguments" value="false"/>
                <!-- always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page -->
                <property name="returnPageInfo" value="none"/>
            </plugin>
        </plugins>
    </configuration>

    三、PageHelper的使用方法,PageHelper.startPage(pageNum, pageSize)只作用离它最近的一个查询,更多与分页相关的信息我们都可以在page对象中拿到,完全可以满足各种情况下的分页查询。

            @Test
    public void testQueryUserList() throws Exception {
    int pageNum=1;
    int pageSize=10;
    Page<User> page = PageHelper.startPage(pageNum, pageSize);
    userDao.queryUserList();
    System.out.println("总共条数:"+page.getTotal());
    for (User user : page.getResult()) {
    System.out.println(user.getName());
    }

    }

    看到如图所示的输出表示分页插件配置成功了

     

    Git代码地址:https://gitee.com/Somta/SpringBoot/tree/master/SpringBoot-mybatis-expand

    原文地址:http://somta.com.cn/#/blog/view/ef507e4e6e28434d9787ec715d406491
    ---------------------
    作者:明天的地平线
    来源:CSDN
    原文:https://blog.csdn.net/husong_/article/details/79923753
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    pixi.js 简单交互事件(点击、缩放、平移)
    w3school
    并发(Concurrent)与并行(Parallel)的区别
    CTime获得当前电脑时间
    NX二次开发-UFUN获得体的表面积,体积,重心等UF_MODL_ask_mass_props_3d
    Jvm故障问题排查以及Jvm调优总结
    jmap命令详解----查看JVM内存使用详情
    jstack命令解析
    年轻带Young GC算法示意图
    【JVM】jstat命令详解---JVM的统计监测工具
  • 原文地址:https://www.cnblogs.com/telwanggs/p/10791883.html
Copyright © 2011-2022 走看看