Spring Boot 整合 Druid 概述 Druid 是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池、插件框架和 SQL 解析器组成。该项目主要是为了扩展 JDBC 的一些限制,可以让程序员实现一些特殊的需求,比如向密钥服务请求凭证、统计 SQL 信息、SQL 性能收集、SQL 注入检查、SQL 翻译等,程序员可以通过定制来实现自己需要的功能。
Druid 是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括 DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。Druid 已经在阿里巴巴部署了超过 600 个应用,经过多年生产环境大规模部署的严苛考验。Druid 是阿里巴巴开发的号称为监控而生的数据库连接池!
引入依赖 在 pom.xml 文件中引入 druid-spring-boot-starter 依赖
1 2 3 4 5 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency>
引入数据库连接依赖
1 2 3 4 5 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
配置 application.yml 在 application.yml 中配置数据库连接
1 2 3 4 5 6 7 8 9 10 11 12 spring: datasource: url: jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource 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
MySQL服务使用docker容器开启
Spring Boot 整合 tk.mybatis 概述 tk.mybatis 是在 MyBatis 框架的基础上提供了很多工具,让开发更加高效
引入依赖 在 pom.xml 文件中引入 mapper-spring-boot-starter 依赖,该依赖会自动引入MyBaits 相关依赖
1 2 3 4 5 <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency>
配置 application.yml 配置 MyBatis
1 2 3 mybatis: type-aliases-package: 实体类的存放路径,如:com.zysheep.spring.boot.mybatis.entity mapper-locations: classpath:mapper/*.xml
创建一个通用的父级接口 主要作用是让 DAO 层的接口继承该接口,以达到使用 tk.mybatis 的目的,特别注意: 该接口不能被扫描到,否则会出错(不能与@SpringBootApplication注解在同一包下,否则会被扫描到)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package tk.mybatis; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; /** *自己的 Mapper * @author :zysheep * @date :Created in 2020/1/11 22:49 * @description:${description} * @version: ${version}$ */ public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> { }
Spring Boot 整合 PageHelper 概述 PageHelper 是 Mybatis 的分页插件,支持多数据库、多数据源。可以简化数据库的分页查询操作,整合过程也极其简单,只需引入依赖即可。
引入依赖 在 pom.xml 文件中引入 pagehelper-spring-boot-starter 依赖
1 2 3 4 5 <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency>
使用 MyBatis 的 Maven 插件生成代码 我们无需手动编写 实体类、DAO、XML 配置文件,只需要使用 MyBatis 提供的一个 Maven 插件就可以自动生成所需的各种文件便能够满足基本的业务需求,如果业务比较复杂只需要修改相关文件即可。
配置插件 在 pom.xml 文件中增加 mybatis-generator-maven-plugin 插件,configurationFile:自动生成所需的配置文件路径
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 <build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.4</version> </dependency> </dependencies> </plugin> </plugins> </build>
自动生成的配置 在 src/main/resources/generator/ 目录下创建 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 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 引入数据库连接配置 --> <properties resource="jdbc.properties"/> <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <!-- 配置 tk.mybatis 插件--> <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> <property name="mappers" value="cn.tk.mybatis.MyMapper"/> </plugin> <!-- 配置数据库连接 --> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <!-- 配置实体类存放路径 --> <javaModelGenerator targetPackage="cn.panyucable.pojo" targetProject="src/main/java"/> <!-- 配置 XML 存放路径 --> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> <!-- 配置 DAO 存放路径 --> <javaClientGenerator targetPackage="cn.panyucable.mapper" targetProject="src/main/java" type="XMLMAPPER"/> <!-- 配置需要指定生成的数据库和表,% 代表所有表 --> <table catalog="panyucable_cn" tableName="%"> <!-- mysql 配置 --> <generatedKey column="id" sqlStatement="Mysql" identity="true"/> </table> </context> </generatorConfiguration>
配置数据源 在 src/main/resources 目录下创建 jdbc.properties 数据源配置:
1 2 3 4 5 # MySQL 8.x: com.mysql.cj.jdbc.Driver jdbc.driverClass=com.mysql.jdbc.Driver jdbc.connectionURL=jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false jdbc.username=root jdbc.password=123456
插件自动生成命令 1 mvn mybatis-generator:generate
测试 MyBatis 操作数据库 使用 tk.mybatis 操作数据库 修改入口类 需要使用 @MapperScan 注解来指定 Mapper 接口的路径,注意: 这里的 @MapperScan 注解是 tk.mybatis.spring.annotation.MapperScan包下的
1 2 3 4 5 6 7 8 @SpringBootApplication @MapperScan(basePackages = "com.zysheep.spring.boot.mybatis.mapper") public class HelloSpringBootApplication { public static void main(String[] args) { SpringApplication.run(HelloSpringBootApplication.class, args); } }
创建测试类 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 @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("Lusifer"); tbUser.setPassword("123456"); tbUser.setPhone("15888888888"); tbUser.setEmail("topsale@vip.qq.com"); tbUser.setCreated(new Date()); tbUser.setUpdated(new Date()); // 插入数据 tbUserMapper.insert(tbUser); } /** * 测试删除数据 */ @Test public void testDelete() { // 构造条件,等同于 DELETE from tb_user WHERE username = 'Lusifer' Example example = new Example(TbUser.class); example.createCriteria().andEqualTo("username", "Lusifer"); // 删除数据 tbUserMapper.deleteByExample(example); } /** * 测试修改数据 */ @Test public void testUpdate() { // 构造条件 Example example = new Example(TbUser.class); example.createCriteria().andEqualTo("username", "Lusifer"); // 构造一条测试数据 TbUser tbUser = new TbUser(); tbUser.setUsername("LusiferNew"); tbUser.setPassword("123456"); tbUser.setPhone("15888888888"); tbUser.setEmail("topsale@vip.qq.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()); } } /** * 测试分页查询 */ @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()); } } }
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 //当前页 private int pageNum; //每页的数量 private int pageSize; //当前页的数量 private int size; //由于startRow和endRow不常用,这里说个具体的用法 //可以在页面中"显示startRow到endRow 共size条数据" //当前页面第一个元素在数据库中的行号 private int startRow; //当前页面最后一个元素在数据库中的行号 private int endRow; //总记录数 private long total; //总页数 private int pages; //结果集 private List<T> list; //前一页 private int prePage; //下一页 private int nextPage; //是否为第一页 private boolean isFirstPage = false; //是否为最后一页 private boolean isLastPage = false; //是否有前一页 private boolean hasPreviousPage = false; //是否有下一页 private boolean hasNextPage = false; //导航页码数 private int navigatePages; //所有导航页号 private int[] navigatepageNums; //导航条上的第一页 private int navigateFirstPage; //导航条上的最后一页 private int navigateLastPage;
TkMybatis的常用方法介绍 Select
List select(T record);
T selectByPrimaryKey(Object key);
根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
List selectAll();
查询全部结果,select(null)方法能达到同样的效果
T selectOne(T record);
根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
int selectCount(T record);
Insert
int insert(T record);
保存一个实体,null的属性也会保存,不会使用数据库默认值
int insertSelective(T record);
保存一个实体,null的属性不会保存,会使用数据库默认值
Update
int updateByPrimaryKey(T record);
int updateByPrimaryKeySelective(T record);
Delete
int delete(T record);
int deleteByPrimaryKey(Object key);
根据主键字段进行删除,方法参数必须包含完整的主键属性
Example方法
List selectByExample(Object example);
根据Example条件进行查询
重点: 这个查询支持通过 Example 类指定查询列,通过 selectProperties 方法指定查询列
int selectCountByExample(Object example);
int updateByExample(@Param(“record”) T record, @Param(“example”) Object example);
根据Example条件更新实体 record 包含的全部属性,null值会被更新
int updateByExampleSelective(@Param(“record”) T record, @Param(“example”) Object example);
根据Example条件更新实体 record 包含的不是null的属性值
int deleteByExample(Object example);
Example 使用方法详解 Example用于添加条件,相当where后面的部分
作用:
example用来放一些去重,排序,分类,分页等信息
criteria用来传字段参数
常用的方法及使用说明:
1 2 3 首先进行初始化: Example example = new Example(实体类.class); Example.Criteria criteria = example.createCriteria();
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 添加升序排列条件,DESC为降序: example.setOrderByClause("字段名 ASC"); 去除重复,boolean型,true为选择不重复的记录: example.setDistinct(false) 添加字段xxx为null的条件: criteria.andXxxIsNull 添加字段xxx不为null的条件: criteria.andXxxIsNotNull 添加xxx字段等于value条件: criteria.andXxxEqualTo(value) 添加xxx字段不等于value条件: criteria.andXxxNotEqualTo(value) 添加xxx字段大于value条件: criteria.andXxxGreaterThan(value) 添加xxx字段大于等于value条件: criteria.andXxxGreaterThanOrEqualTo(value) 添加xxx字段小于value条件: criteria.andXxxLessThan(value) 添加xxx字段小于等于value条件: criteria.andXxxLessThanOrEqualTo(value) 添加xxx字段值在List<?>条件: criteria.andXxxIn(List<?>) 添加xxx字段值不在List<?>条件: criteria.andXxxNotIn(List<?>) 添加xxx字段值为value的模糊查询条件: criteria.andXxxLike("%"+value+"%") 添加xxx字段值不为value的模糊查询条件: criteria.andXxxNotLike("%"+value+"%"") 添加xxx字段值在value1和value2之间条件: criteria.andXxxBetween(value1,value2) 添加xxx字段值不在value1和value2之间条件: criteria.andXxxNotBetween(value1,value2)
需要注意的点:
首先要生成实例化及实例对应的example,然后记住一定要先初始化;
使用and和or方法进行判断时,“与”、“或”的逻辑关系分清,避免出现拿数据时出现重复拿或者逻辑冲突拿不到的情况;
mapper.selectByExample()方法里面应该传入的参数是example对象,而非其他的。
附:完整的 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 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 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zysheep</groupId> <artifactId>spring-boot-mybatis</artifactId> <version>1.0.0-SNAPSHOT</version> <name>spring-boot-mybatis</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <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> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.4</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>