Spring Boot - 整合 Druid+tk.mybatis+PageHelper

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用版 2核4GB 50GB
简介: Spring Boot - 整合 Druid+tk.mybatis+PageHelper

Druid


简介


Druid 是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池、插件框架和 SQL 解析器组成。该项目主要是为了扩展 JDBC 的一些限制,可以让程序员实现一些特殊的需求,比如向密钥服务请求凭证、统计 SQL 信息、SQL 性能收集、SQL 注入检查、SQL 翻译等,程序员可以通过定制来实现自己需要的功能。


Druid 是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括 DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。Druid 已经在阿里巴巴部署了超过 600 个应用,经过多年生产环境大规模部署的严苛考验。Druid 是阿里巴巴开发的号称为监控而生的数据库连接池!


引入依赖


pom.xml 文件中引入 druid-spring-boot-starter 依赖


<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>


引入数据库连接依赖


<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>


配置 application.yml


application.yml 中配置数据库连接


spring:
  datasource:
    druid:
      url: jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      # MySQL 8.x: com.mysql.cj.jdbc.Driver
      driver-class-name: com.mysql.jdbc.Driver


tk.mybatis


简介


tk.mybatis 是在 MyBatis 框架的基础上提供了很多工具,让开发更加高效


引入依赖


pom.xml 文件中引入 mapper-spring-boot-starter 依赖,该依赖会自动引入 MyBatis 相关依赖


<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>


配置 application.xml


配置 MyBatis


mybatis:
    type-aliases-package: 实体类的存放路径,如:com.bianya.hello.spring.boot.entity
    mapper-locations: classpath:mapper/*.xml


创建一个通用的父级接口


主要作用是让 DAO 层的接口继承该接口,以达到使用 tk.mybatis 的目的


package tx.mybatis;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
/**
 * 自己的 Mapper
 * 特别注意,该接口不能被扫描到,否则会出错
 * <p>Title: MyMapper</p>
 * <p>Description: </p>
 *
 * @author Administrator
 * @version 1.0.0
 * @date 2021/04/27 21:57
 */
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

修改入口类


需要使用 @MapperScan 注解来指定 Mapper 接口的路径


PS: 注意这里的 @MapperScan 注解是 tk.mybatis.spring.annotation.MapperScan;包下的


package com.bianya.hello.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan(basePackages = "com.bianya.hello.spring.boot.mapper")
public class HelloSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloSpringBootApplication.class, args);
    }
}


创建测试类


package com.bianya.hello.spring.boot;
import com.bianya.hello.spring.boot.entity.TbUser;
import com.bianya.hello.spring.boot.mapper.TbUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloSpringBootApplication.class)
@Transactional
@Rollback
public class MyBatisTests {
    /**
     * 注入数据查询接口
     */
    @Autowired
    private TbUserMapper tbUserMapper;
    /**
     * 测试插入数据
     */
    @Test
    public void testInsert() {
        // 构造一条测试数据
        TbUser tbUser = new TbUser();
        tbUser.setUsername("test");
        tbUser.setPassword("123456");
        tbUser.setPhone("10000000000");
        tbUser.setEmail("test@test.com");
        tbUser.setCreated(new Date());
        tbUser.setUpdated(new Date());
        // 插入数据
        tbUserMapper.insert(tbUser);
    }
    /**
     * 测试删除数据
     */
    @Test
    public void testDelete() {
        // 构造条件,等同于 DELETE from tb_user WHERE username = 'test'
        Example example = new Example(TbUser.class);
        example.createCriteria().andEqualTo("username", "test");
        // 删除数据
        tbUserMapper.deleteByExample(example);
    }
    /**
     * 测试修改数据
     */
    @Test
    public void testUpdate() {
        // 构造条件
        Example example = new Example(TbUser.class);
        example.createCriteria().andEqualTo("username", "test");
        // 构造一条测试数据
        TbUser tbUser = new TbUser();
        tbUser.setUsername("testNew");
        tbUser.setPassword("123456");
        tbUser.setPhone("10000000000");
        tbUser.setEmail("test@test.com");
        tbUser.setCreated(new Date());
        tbUser.setUpdated(new Date());
        // 修改数据
        tbUserMapper.updateByExample(tbUser, example);
    }
    /**
     * 测试查询集合
     */
    @Test
    public void testSelect() {
        List<TbUser> tbUsers = tbUserMapper.selectAll();
        for (TbUser tbUser : tbUsers) {
            System.out.println(tbUser.getUsername());
        }
    }
}


PageHelper


简介


PageHelper 是 MyBatis 的分页插件,支持多数据库、多数据源。可以简化数据库的分页查询操作,整合过程也极其简单,只需引入依赖即可。


引入依赖


pom.xml 文件中引入 pagehelper-spring-boot-starter 依赖


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


创建测试类


package com.bianya.hello.spring.boot;
import com.bianya.hello.spring.boot.entity.TbUser;
import com.bianya.hello.spring.boot.mapper.TbUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloSpringBootApplication.class)
@Transactional
@Rollback
public class MyBatisTests {
 /**
     * 注入数据查询接口
     */
    @Autowired
    private TbUserMapper tbUserMapper;
    /**
     * 测试查询集合
     */
    @Test
    public void testSelect() {
        List<TbUser> tbUsers = tbUserMapper.selectAll();
        for (TbUser tbUser : tbUsers) {
            System.out.println(tbUser.getUsername());
        }
    }
     /**
     * 测试分页查询
     */
    @Test
    public void testPage() {
        // PageHelper 使用非常简单,只需要设置页码和每页显示笔数即可
        PageHelper.startPage(0, 2);
        // 设置分页查询条件
        Example example = new Example(TbUser.class);
        PageInfo<TbUser> pageInfo = new PageInfo<>(tbUserMapper.selectByExample(example));
        // 获取查询结果
        List<TbUser> tbUsers = pageInfo.getList();
        for (TbUser tbUser : tbUsers) {
            System.out.println(tbUser.getUsername());
        }
    }
}
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
15小时前
|
SQL Java 数据库连接
Spring Boot整合MyBatis
Spring Boot整合MyBatis
|
15小时前
|
Java 数据库连接 Spring
Spring 整合 MyBatis 底层源码解析
Spring 整合 MyBatis 底层源码解析
|
1天前
|
Java 数据库连接 数据库
Spring Boot 集成 MyBatis-Plus 总结
Spring Boot 集成 MyBatis-Plus 总结
|
1天前
|
XML Java 数据库连接
SpringBoot(九)之整合mybatis
mybatis-spring-boot-starter 可以简化在 Spring Boot 项目中集成 MyBatis 的过程,并且事务管理也会自动配置。在 Spring Boot 2.x 及以上版本中,只需添加相应的依赖和配置,即可启用事务管理。
4 0
|
3天前
|
Java 关系型数据库 MySQL
3.MyBatis和SpringBoot整合及MyBatis-plus与SpringBoot整合
3.MyBatis和SpringBoot整合及MyBatis-plus与SpringBoot整合
11 0
|
3天前
springboot2.4.5使用pagehelper分页插件
springboot2.4.5使用pagehelper分页插件
6 0
|
3天前
|
Java Maven
springboot项目打jar包后,如何部署到服务器
springboot项目打jar包后,如何部署到服务器
13 1
|
3天前
|
Java 数据库连接 数据库
Springboot整合mybatis注解版(202005)
Springboot整合mybatis注解版(202005)
13 3
|
3天前
|
安全 前端开发 Java
挑战5分钟内基于Springboot+SpringMVC+Mybatis-plus快速构建web后端三层架构
挑战5分钟内基于Springboot+SpringMVC+Mybatis-plus快速构建web后端三层架构
9 1
|
3天前
|
运维 Java 关系型数据库
Spring运维之boot项目bean属性的绑定读取与校验
Spring运维之boot项目bean属性的绑定读取与校验
12 2