springboot集成druid、mybatis以及pagehelper

释放双眼,带上耳机,听听看~!

文章目录

  • 1、springboot配置数据库连接池druid

  • 简介

    • 2、springboot整合mybatis
    • 3、springboot整合pagehelper

1、springboot配置数据库连接池druid

druid学习地址:https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

简介

DRUID是阿里巴巴开源平台上一个数据库连接池实现,它结合了C3P0、DBCP、PROXOOL等DB池的优点,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况,可以说是针对监控而生的DB连接池,据说是目前最好的连接池。

新建springboot项目注意一下几点:
springboot集成druid、mybatis以及pagehelper
相关pom依赖(druid所需pom依赖)


1
2
3
4
5
6
7
8
9
10
11
12
1<dependency>
2     <groupId>com.alibaba</groupId>
3     <artifactId>druid-spring-boot-starter</artifactId>
4     <version>1.1.10</version>
5  </dependency>
6<dependency>
7    <groupId>org.springframework</groupId>
8    <artifactId>spring-aspects</artifactId>
9</dependency>
10
11
12

配置application.yml
application.yml配置druid
springboot默认数据源是
org.apache.tomcat.jdbc.pool.DataSource

倘若在Idea中已经安装好jrebel,那就只需配置一下的


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
1spring:
2  datasource:
3    #1.JDBC
4    type: com.alibaba.druid.pool.DruidDataSource
5    driver-class-name: com.mysql.jdbc.Driver
6    url: jdbc:mysql://localhost:3306/wyy?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
7    username: root
8    password: 123
9    druid:
10      #2.连接池配置
11      #初始化连接池的连接数量 大小,最小,最大
12      initial-size: 5
13      min-idle: 5
14      max-active: 20
15      #配置获取连接等待超时的时间
16      max-wait: 60000
17      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
18      time-between-eviction-runs-millis: 60000
19      # 配置一个连接在池中最小生存的时间,单位是毫秒
20      min-evictable-idle-time-millis: 30000
21      validation-query: SELECT 1 FROM DUAL
22      test-while-idle: true
23      test-on-borrow: true
24      test-on-return: false
25      # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
26      pool-prepared-statements: true
27      max-pool-prepared-statement-per-connection-size: 20
28      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
29      filter:
30        stat:
31          merge-sql: true
32          slow-sql-millis: 5000
33      #3.基础监控配置
34      web-stat-filter:
35        enabled: true
36        url-pattern: /*
37        #设置不统计哪些URL
38        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
39        session-stat-enable: true
40        session-stat-max-count: 100
41      stat-view-servlet:
42        enabled: true
43        url-pattern: /druid/*
44        reset-enable: true
45        #设置监控页面的登录名和密码
46        login-username: admin
47        login-password: admin
48        allow: 127.0.0.1
49        #deny: 192.168.1.100
50server:
51  port: 8080
52  servlet:
53    context-path: /
54
55

如果没有按照jrebel那就还需要加如下配置:
application.yml配置devtools热加载


1
2
3
4
5
6
7
8
9
10
11
12
13
1spring
2  #devtools热加载
3  devtools:
4    restart:
5      #启用热加载
6      enabled: true
7      #添加那个目录的文件不需要restart
8      exclude: static/*
9      #添加那个目录的文件需要restart
10      additional-paths: src/main/java
11
12
13

springboot整合druid成功截图
启动SpringBoot项目访问druid, http://localhost:tomcat端口号/项目名称/druid/

springboot集成druid、mybatis以及pagehelper
**HelloController **


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
1package com.wyy.springboot03.controller;
2
3import org.springframework.stereotype.Controller;
4import org.springframework.web.bind.annotation.RequestMapping;
5import org.springframework.web.bind.annotation.RestController;
6
7/**
8 * @author 秃头集团王某
9 * @company 秃头公司
10 * @create 2019-11-11  9:30
11 */
12@RestController
13@RequestMapping("/demo")
14public class HelloController {
15    @RequestMapping("/say1")
16    public String say1(){
17        return "张三说!!!!  ";
18    }
19
20    @RequestMapping("/say2")
21    public String say2(){
22        try {
23            Thread.sleep(2000);
24        } catch (InterruptedException e) {
25            e.printStackTrace();
26        }
27        return "李四说!!!!  ";
28    }
29
30    @RequestMapping("/say3")
31    public String say3(){
32        try {
33            Thread.sleep(5000);
34        } catch (InterruptedException e) {
35            e.printStackTrace();
36        }
37        return "王五说!!!!  ";
38    }
39}
40
41
42

可以查看方法的性能
springboot集成druid、mybatis以及pagehelper

2、springboot整合mybatis

MyBatis-Spring-Boot-Starter依赖将会提供如下:

  1. 自动检测现有的DataSource。
  2. 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递。
  3. 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
  4. 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。

就是说,使用了该Starter之后,只需要定义一个DataSource即可(application.properties或application.yml中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

springboot整合mybatis逆向生成插件
相关pom依赖


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
1<!--更改springboot中的mysql版本,逆向生成不兼容高版本-->
2<mysql.version>5.1.44</mysql.version>
3
4<dependency>
5    <groupId>mysql</groupId>
6    <artifactId>mysql-connector-java</artifactId>
7    <version>${mysql.version}</version>
8    <scope>runtime</scope>
9</dependency>
10
11<resources>
12    <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
13    <resource>
14        <directory>src/main/java</directory>
15        <includes>
16            <include>**/*.xml</include>
17        </includes>
18    </resource>
19    <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
20    <resource>
21        <directory>src/main/resources</directory>
22        <includes>
23            <include>*.properties</include>
24            <include>*.xml</include>
25            <include>*.yml</include>
26        </includes>
27    </resource>
28</resources>
29
30<plugin>
31    <groupId>org.mybatis.generator</groupId>
32    <artifactId>mybatis-generator-maven-plugin</artifactId>
33    <version>1.3.2</version>
34    <dependencies>
35        <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
36        <dependency>
37            <groupId>mysql</groupId>
38            <artifactId>mysql-connector-java</artifactId>
39            <version>${mysql.version}</version>
40        </dependency>
41    </dependencies>
42    <configuration>
43        <overwrite>true</overwrite>
44    </configuration>
45</plugin>
46
47
48

generatorConfig.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
1<?xml version="1.0" encoding="UTF-8" ?>
2<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
3        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
4<generatorConfiguration>
5    <!-- 引入配置文件 -->
6    <properties resource="jdbc.properties"/>
7
8    <!--指定数据库jdbc驱动jar包的位置-->
9    <classPathEntry
10            location="E:\\kfapp\\maven_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
11
12    <!-- 一个数据库一个context -->
13    <context id="infoGuardian">
14        <!-- 注释 -->
15        <commentGenerator>
16            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
17            <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
18        </commentGenerator>
19
20        <!-- jdbc连接 -->
21        <jdbcConnection driverClass="${jdbc.driver}"
22                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
23
24        <!-- 类型转换 -->
25        <javaTypeResolver>
26            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
27            <property name="forceBigDecimals" value="false"/>
28        </javaTypeResolver>
29
30        <!-- 01 指定javaBean生成的位置 -->
31        <!-- targetPackage:指定生成的model生成所在的包名 -->
32        <!-- targetProject:指定在该项目下所在的路径  -->
33        <javaModelGenerator targetPackage="com.wyy.springboot03.entity"
34                            targetProject="src/main/java">
35            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
36            <property name="enableSubPackages" value="false"/>
37            <!-- 是否对model添加构造函数 -->
38            <property name="constructorBased" value="true"/>
39            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
40            <property name="trimStrings" value="false"/>
41            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
42            <property name="immutable" value="false"/>
43        </javaModelGenerator>
44
45        <!-- 02 指定sql映射文件生成的位置 -->
46        <sqlMapGenerator targetPackage="com.wyy.springboot03.mapper"
47                         targetProject="src/main/java">
48            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
49            <property name="enableSubPackages" value="false"/>
50        </sqlMapGenerator>
51
52        <!-- 03 生成XxxMapper接口 -->
53        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
54        <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
55        <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
56        <javaClientGenerator targetPackage="com.wyy.springboot03.mapper"
57                             targetProject="src/main/java" type="XMLMAPPER">
58            <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
59            <property name="enableSubPackages" value="false"/>
60        </javaClientGenerator>
61
62        <!-- 配置表信息 -->
63        <!-- schema即为数据库名 -->
64        <!-- tableName为对应的数据库表 -->
65        <!-- domainObjectName是要生成的实体类 -->
66        <!-- enable*ByExample是否生成 example类 -->
67
68        <table schema="" tableName="t_mvc_book" domainObjectName="Book"
69               enableCountByExample="false" enableDeleteByExample="false"
70               enableSelectByExample="false" enableUpdateByExample="false">
71            <property name="useActualColumnNames" value="true" />
72        </table>
73
74
75    </context>
76</generatorConfiguration>
77
78
79

逆向生成集成到maven中的命令

mybatis-generator:generate -e
springboot集成druid、mybatis以及pagehelperspringboot集成druid、mybatis以及pagehelper


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
1<?xml version="1.0" encoding="UTF-8" ?>
2<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
3        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
4<generatorConfiguration>
5    <!-- 引入配置文件 -->
6    <properties resource="jdbc.properties"/>
7
8    <!--指定数据库jdbc驱动jar包的位置-->
9    <classPathEntry
10            location="E:\\kfapp\\maven_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
11
12    <!-- 一个数据库一个context -->
13    <context id="infoGuardian">
14        <!-- 注释 -->
15        <commentGenerator>
16            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
17            <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
18        </commentGenerator>
19
20        <!-- jdbc连接 -->
21        <jdbcConnection driverClass="${jdbc.driver}"
22                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
23
24        <!-- 类型转换 -->
25        <javaTypeResolver>
26            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
27            <property name="forceBigDecimals" value="false"/>
28        </javaTypeResolver>
29
30        <!-- 01 指定javaBean生成的位置 -->
31        <!-- targetPackage:指定生成的model生成所在的包名 -->
32        <!-- targetProject:指定在该项目下所在的路径  -->
33        <javaModelGenerator targetPackage="com.wyy.springboot03.entity"
34                            targetProject="src/main/java">
35            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
36            <property name="enableSubPackages" value="false"/>
37            <!-- 是否对model添加构造函数 -->
38            <property name="constructorBased" value="true"/>
39            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
40            <property name="trimStrings" value="false"/>
41            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
42            <property name="immutable" value="false"/>
43        </javaModelGenerator>
44
45        <!-- 02 指定sql映射文件生成的位置 -->
46        <sqlMapGenerator targetPackage="com.wyy.springboot03.mapper"
47                         targetProject="src/main/java">
48            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
49            <property name="enableSubPackages" value="false"/>
50        </sqlMapGenerator>
51
52        <!-- 03 生成XxxMapper接口 -->
53        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
54        <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
55        <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
56        <javaClientGenerator targetPackage="com.wyy.springboot03.mapper"
57                             targetProject="src/main/java" type="XMLMAPPER">
58            <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
59            <property name="enableSubPackages" value="false"/>
60        </javaClientGenerator>
61
62        <!-- 配置表信息 -->
63        <!-- schema即为数据库名 -->
64        <!-- tableName为对应的数据库表 -->
65        <!-- domainObjectName是要生成的实体类 -->
66        <!-- enable*ByExample是否生成 example类 -->
67
68        <table schema="" tableName="t_mvc_book" domainObjectName="Book"
69               enableCountByExample="false" enableDeleteByExample="false"
70               enableSelectByExample="false" enableUpdateByExample="false">
71            <property name="useActualColumnNames" value="true" />
72        </table>
73
74
75    </context>
76</generatorConfiguration>
77
78
79

使用@Repository注解,在启动类中添加@MapperScan(“xxxx”)注解,用于扫描Mapper类的包。扫描多个包:@MapperScan({”com.wyy.springboot03.dao”,”com.wyy.springboot03.entity”})
//启用事物管理器
@EnableTransactionManagement

Springboot03Application


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1package com.wyy.springboot03;
2
3import org.mybatis.spring.annotation.MapperScan;
4import org.springframework.boot.SpringApplication;
5import org.springframework.boot.autoconfigure.SpringBootApplication;
6
7@MapperScan("com.wyy.springboot03.mapper")
8@SpringBootApplication
9public class Springboot03Application {
10
11    public static void main(String[] args) {
12        SpringApplication.run(Springboot03Application.class, args);
13    }
14
15}
16
17
18

Book


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
1package com.wyy.springboot03.entity;
2
3import lombok.ToString;
4
5@ToString
6public class Book {
7    private Integer bid;
8
9    private String bname;
10
11    private Float price;
12
13    public Book(Integer bid, String bname, Float price) {
14        this.bid = bid;
15        this.bname = bname;
16        this.price = price;
17    }
18
19    public Book() {
20        super();
21    }
22
23    public Integer getBid() {
24        return bid;
25    }
26
27    public void setBid(Integer bid) {
28        this.bid = bid;
29    }
30
31    public String getBname() {
32        return bname;
33    }
34
35    public void setBname(String bname) {
36        this.bname = bname;
37    }
38
39    public Float getPrice() {
40        return price;
41    }
42
43    public void setPrice(Float price) {
44        this.price = price;
45    }
46}
47
48

BookMapper


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1package com.wyy.springboot03.mapper;
2
3import com.wyy.springboot03.entity.Book;
4import org.springframework.stereotype.Repository;
5
6import java.util.List;
7import java.util.Map;
8
9@Repository
10public interface BookMapper {
11    int deleteByPrimaryKey(Integer bid);
12
13    int insert(Book record);
14
15    int insertSelective(Book record);
16
17    Book selectByPrimaryKey(Integer bid);
18
19    int updateByPrimaryKeySelective(Book record);
20
21    int updateByPrimaryKey(Book record);
22
23    List<Map> bookPager(Map map);
24}
25
26

BookMapper.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
1<?xml version="1.0" encoding="UTF-8" ?>
2<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
3<mapper namespace="com.wyy.springboot03.mapper.BookMapper" >
4  <resultMap id="BaseResultMap" type="com.wyy.springboot03.entity.Book" >
5    <constructor >
6      <idArg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
7      <arg column="bname" jdbcType="VARCHAR" javaType="java.lang.String" />
8      <arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
9    </constructor>
10  </resultMap>
11  <sql id="Base_Column_List" >
12    bid, bname, price
13  </sql>
14  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
15    select
16    <include refid="Base_Column_List" />
17    from t_mvc_book
18    where bid = #{bid,jdbcType=INTEGER}
19  </select>
20  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
21    delete from t_mvc_book
22    where bid = #{bid,jdbcType=INTEGER}
23  </delete>
24  <insert id="insert" parameterType="com.wyy.springboot03.entity.Book" >
25    insert into t_mvc_book (bid, bname, price
26      )
27    values (#{bid,jdbcType=INTEGER}, #{bname,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
28      )
29  </insert>
30  <insert id="insertSelective" parameterType="com.wyy.springboot03.entity.Book" >
31    insert into t_mvc_book
32    <trim prefix="(" suffix=")" suffixOverrides="," >
33      <if test="bid != null" >
34        bid,
35      </if>
36      <if test="bname != null" >
37        bname,
38      </if>
39      <if test="price != null" >
40        price,
41      </if>
42    </trim>
43    <trim prefix="values (" suffix=")" suffixOverrides="," >
44      <if test="bid != null" >
45        #{bid,jdbcType=INTEGER},
46      </if>
47      <if test="bname != null" >
48        #{bname,jdbcType=VARCHAR},
49      </if>
50      <if test="price != null" >
51        #{price,jdbcType=REAL},
52      </if>
53    </trim>
54  </insert>
55  <update id="updateByPrimaryKeySelective" parameterType="com.wyy.springboot03.entity.Book" >
56    update t_mvc_book
57    <set >
58      <if test="bname != null" >
59        bname = #{bname,jdbcType=VARCHAR},
60      </if>
61      <if test="price != null" >
62        price = #{price,jdbcType=REAL},
63      </if>
64    </set>
65    where bid = #{bid,jdbcType=INTEGER}
66  </update>
67  <update id="updateByPrimaryKey" parameterType="com.wyy.springboot03.entity.Book" >
68    update t_mvc_book
69    set bname = #{bname,jdbcType=VARCHAR},
70      price = #{price,jdbcType=REAL}
71    where bid = #{bid,jdbcType=INTEGER}
72  </update>
73  <select id="bookPager" resultType="java.util.Map" parameterType="java.util.Map">
74    select * from t_mvc_book
75    <where>
76      <if test="bname != null">
77        bname like concat('%',#{bname},'%')
78      </if>
79    </where>
80  </select>
81
82</mapper>
83
84

BookService


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1package com.wyy.springboot03.service;
2
3import com.wyy.springboot03.entity.Book;
4import com.wyy.springboot03.utils.PageBean;
5
6import java.util.List;
7import java.util.Map;
8
9/**
10 * @author 秃头集团王某
11 * @company 秃头公司
12 * @create 2019-11-11  10:13
13 */
14public interface BookService  {
15    int deleteByPrimaryKey(Integer bid);
16    Book selectByPrimaryKey(Integer bid);
17    List<Map> bookPager(Map map, PageBean pageBean);
18}
19
20
21

BookServiceImpl
package com.wyy.springboot03.service.impl;

import com.wyy.springboot03.entity.Book;
import com.wyy.springboot03.mapper.BookMapper;
import com.wyy.springboot03.service.BookService;
import com.wyy.springboot03.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**

  • @author 秃头集团王某

  • @company 秃头公司

  • @create 2019-11-11 10:16

*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public int deleteByPrimaryKey(Integer bid) {
return bookMapper.deleteByPrimaryKey(bid);
}

@Override
public Book selectByPrimaryKey(Integer bid) {
return bookMapper.selectByPrimaryKey(bid);
}

@Override
public List
bookPager(Map map, PageBean pageBean) {
return bookMapper.bookPager(map);
}
}

3、springboot整合pagehelper

导入相关pom依赖


1
2
3
4
5
6
7
8
1<dependency>
2            <groupId>com.github.pagehelper</groupId>
3            <artifactId>pagehelper-spring-boot-starter</artifactId>
4            <version>1.2.3</version>
5        </dependency>
6
7
8

配置application.yml文件


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1#pagehelper分页插件配置
2pagehelper:
3  helperDialect: mysql
4  reasonable: true
5  supportMethodsArguments: true
6  params: count=countSql
7
8#显示日志
9logging:
10  level:
11    com.wyy.springboot03.mapper: debug
12
13
14

jdbc.properties


1
2
3
4
5
6
1jdbc.driver=com.mysql.jdbc.Driver
2jdbc.url=jdbc:mysql://localhost:3306/wyy?useUnicode=true&characterEncoding=UTF-8
3jdbc.username=root
4jdbc.password=123
5
6

PageBean


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
1package com.wyy.springboot03.utils;
2
3import javax.servlet.http.HttpServletRequest;
4import java.io.Serializable;
5import java.util.Map;
6
7public class PageBean implements Serializable {
8
9   private static final long serialVersionUID = 2422581023658455731L;
10
11  //页码
12  private int page=1;
13  //每页显示记录数
14  private int rows=10;
15  //总记录数
16  private int total=0;
17  //是否分页
18  private boolean isPagination=true;
19  //上一次的请求路径
20  private String url;
21  //获取所有的请求参数
22  private Map<String,String[]> map;
23 
24  public PageBean() {
25      super();
26  }
27 
28  //设置请求参数
29  public void setRequest(HttpServletRequest req) {
30      String page=req.getParameter("page");
31      String rows=req.getParameter("rows");
32      String pagination=req.getParameter("pagination");
33      this.setPage(page);
34      this.setRows(rows);
35      this.setPagination(pagination);
36      this.url=req.getContextPath()+req.getServletPath();
37      this.map=req.getParameterMap();
38  }
39  public String getUrl() {
40      return url;
41  }
42
43  public void setUrl(String url) {
44      this.url = url;
45  }
46
47  public Map<String, String[]> getMap() {
48      return map;
49  }
50
51  public void setMap(Map<String, String[]> map) {
52      this.map = map;
53  }
54
55  public int getPage() {
56      return page;
57  }
58
59  public void setPage(int page) {
60      this.page = page;
61  }
62 
63  public void setPage(String page) {
64      if(null!=page&&!"".equals(page.trim()))
65          this.page = Integer.parseInt(page);
66  }
67
68  public int getRows() {
69      return rows;
70  }
71
72  public void setRows(int rows) {
73      this.rows = rows;
74  }
75 
76  public void setRows(String rows) {
77      if(null!=rows&&!"".equals(rows.trim()))
78          this.rows = Integer.parseInt(rows);
79  }
80
81  public int getTotal() {
82      return total;
83  }
84
85  public void setTotal(int total) {
86      this.total = total;
87  }
88 
89  public void setTotal(String total) {
90      this.total = Integer.parseInt(total);
91  }
92
93  public boolean isPagination() {
94      return isPagination;
95  }
96 
97  public void setPagination(boolean isPagination) {
98      this.isPagination = isPagination;
99  }
100
101 public void setPagination(String isPagination) {
102     if(null!=isPagination&&!"".equals(isPagination.trim()))
103         this.isPagination = Boolean.parseBoolean(isPagination);
104 }
105
106 /**
107  * 获取分页起始标记位置
108  * @return
109  */
110 public int getStartIndex() {
111     //(当前页码-1)*显示记录数
112     return (this.getPage()-1)*this.rows;
113 }
114
115 /**
116  * 末页
117  * @return
118  */
119 public int getMaxPage() {
120     int totalpage=this.total/this.rows;
121     if(this.total%this.rows!=0)
122         totalpage++;
123     return totalpage;
124 }
125
126 /**
127  * 下一页
128  * @return
129  */
130 public int getNextPage() {
131     int nextPage=this.page+1;
132     if(this.page>=this.getMaxPage())
133         nextPage=this.getMaxPage();
134     return nextPage;
135 }
136
137 /**
138  * 上一页
139  * @return
140  */
141 public int getPreivousPage() {
142     int previousPage=this.page-1;
143     if(previousPage<1)
144         previousPage=1;
145     return previousPage;
146 }
147
148 @Override
149 public String toString() {
150     return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
151             + "]";
152 }
153}
154
155
156

Springboot03ApplicationTests


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
1package com.wyy.springboot03;
2
3import com.wyy.springboot03.entity.Book;
4import com.wyy.springboot03.service.BookService;
5import com.wyy.springboot03.utils.PageBean;
6import org.junit.jupiter.api.Test;
7import org.springframework.beans.factory.annotation.Autowired;
8import org.springframework.boot.test.context.SpringBootTest;
9
10import java.util.HashMap;
11import java.util.List;
12import java.util.Map;
13
14@SpringBootTest
15class Springboot03ApplicationTests {
16    @Autowired
17    private BookService bookService;
18    @Test
19    public void deleteByPrimaryKey(){
20        bookService.deleteByPrimaryKey(11);
21    }
22
23    @Test
24    public void selectByPrimaryKey(){
25        Book book = bookService.selectByPrimaryKey(11);
26        System.out.println(book);
27    }
28
29    @Test
30    public void queryAll(){
31        Map map = new HashMap();
32        map.put("bname","不死不灭");
33        PageBean pageBean = new PageBean();
34        pageBean.setPage(3);
35        List<Map> list = bookService.bookPager(map,pageBean);
36        for (Map m : list) {
37            System.out.println(m);
38        }
39        System.out.println(pageBean);
40    }
41
42}
43
44
45

springboot集成druid、mybatis以及pagehelper

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C/C++内存泄漏及检测

2022-1-11 12:36:11

安全经验

NetSPoC 3.2 发布,网络安全策略工具

2011-1-3 11:12:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索