如有神助!阿里P7大牛把Spring Boot讲解得如此透彻,送你上岸

Hello,今天给各位童鞋们分享Spring Boot,赶紧拿出小本子记下来吧!

image.png

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 依赖

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

<version>1.1.10</version>
复制代码

**引入数据库连接依赖
mysql

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>
复制代码

配置 application.yml

在 application.yml中配置数据库连接

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 相关依赖

<groupId>tk.mybatis</groupId>

<artifactId>mapper-spring-boot-starter</artifactId>

<version>2.0.2</version>
复制代码

配置 MyBatis

mybatis:

   type-aliases-package: 实体类的存放路径,如:com.zysheep.spring.boot.mybatis.entity

mapper-locations: classpath:mapper/*.xml
复制代码

创建一个通用的父级接口

主要作用是让 DAO层的接口继承该接口,以达到使用 tk.mybatis的目的,特别注意: 该接口不能被扫描到,否则会出错

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{version}

*/

public interface MyMapper extends Mapper, MySqlMapper {

}

Spring Boot 整合 PageHelper

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

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

<groupId>com.github.pagehelper</groupId>

<artifactId>pagehelper-spring-boot-starter</artifactId>

<version>1.2.5</version>
复制代码

使用 MyBatis 的 Maven 插件生成代码

我们无需手动编写 实体类、DAO、XML 配置文件,只需要使用 MyBatis 提供的一个 Maven 插件就可以自动生成所需的各种文件便能够满足基本的业务需求,如果业务比较复杂只需要修改相关文件即可。

配置插件

在pom.xml 文件中增加mybatis-generator-maven-plugin 插件,configurationFile:自动生成所需的配置文件路径

image.png

自动生成的配置

在 src/main/resources/generator/目录下创建 generatorConfig.xml

配置文件:

<!-- 引入数据库连接配置 -->

<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>
复制代码

配置数据源

在 src/main/resources目录下创建 jdbc.properties

数据源配置:

# 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=root

插件自动生成命令

mvn mybatis-generator:generate

测试 MyBatis 操作数据库

使用 tk.mybatis 操作数据库

修改入口类

image.png

创建测试类

@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);

}

 * 测试删除数据

public void testDelete() {

    // 构造条件,等同于 DELETE from tb_user WHERE username = 'Lusifer'

    Example example = new Example(TbUser.class);

    example.createCriteria().andEqualTo("username", "Lusifer");

    //删除数据

    tbUserMapper.deleteByExample(example);

 * 测试修改数据

public void testUpdate() {

    // 构造条件

    tbUser.setUsername("LusiferNew");

    // 修改数据

    tbUserMapper.updateByExample(tbUser, example);

 * 测试查询集合

public void testSelect() {

    List<TbUser> tbUsers = tbUserMapper.selectAll();

    for (TbUser tbUser : tbUsers) {

        System.out.println(tbUser.getUsername());

    }

 * 测试分页查询

public void testPage() {

    // PageHelper 使用非常简单,只需要设置页码和每页显示笔数即可

    PageHelper.startPage(0, 2);

    // 设置分页查询条件

    PageInfo<TbUser> pageInfo = new PageInfo<>(tbUserMapper.selectByExample(example));

    // 获取查询结果

    List<TbUser> tbUsers = pageInfo.getList();

//当前页

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);

根据主键更新实体全部字段,null值会被更新

int updateByPrimaryKeySelective(T record);

根据主键更新属性不为null的值

Delete

int delete(T record);

根据实体属性作为条件进行删除,查询条件使用等号

int deleteByPrimaryKey(Object key);

根据主键字段进行删除,方法参数必须包含完整的主键属性

Example方法

List selectByExample(Object example);

根据Example条件进行查询

重点: 这个查询支持通过 Example 类指定查询列,通过 selectProperties 方法指定查询列

int selectCountByExample(Object example);

根据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 使用方法详解

Example用于添加条件,相当where后面的部分

作用:

example

用来放一些去重,排序,分类,分页等信息

criteria

用来传字段参数

常用的方法及使用说明:

首先进行初始化:

Example example = new Example(实体类.class);

Example.Criteria criteria = example.createCriteria();

添加升序排列条件,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

<project xmlns=”maven.apache.org/POM/4.0.0” xmlns:xsi=”www.w3.org/2001/XMLSch…

     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>

        <artifactId>spring-boot-starter-web</artifactId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

        <exclusions>

            <exclusion>

                <groupId>org.junit.vintage</groupId>

                <artifactId>junit-vintage-engine</artifactId>

            </exclusion>

        </exclusions>

        <groupId>com.alibaba</groupId>

        <artifactId>druid-spring-boot-starter</artifactId>

        <version>1.1.10</version>

        <groupId>mysql</groupId>

        <artifactId>mysql-connector-java</artifactId>

        <scope>runtime</scope>

        <groupId>tk.mybatis</groupId>

        <artifactId>mapper-spring-boot-starter</artifactId>

        <version>2.0.2</version>

        <groupId>com.github.pagehelper</groupId>

        <artifactId>pagehelper-spring-boot-starter</artifactId>

        <version>1.2.5</version>

        <groupId>junit</groupId>

        <artifactId>junit</artifactId>

        <version>4.12</version>

</dependencies>

<build>

    <plugins>

        <plugin>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-maven-plugin</artifactId>

        </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>

                    <groupId>tk.mybatis</groupId>

                    <artifactId>mapper</artifactId>

                    <version>3.4.4</version>

            </dependencies>

    </plugins>

</build>
复制代码

好啦,今天的文章就到这里,希望能帮助到屏幕前迷茫的你们!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享