开箱即用之Spring Boot

对于 Spring Boot 的开箱即用的思想,想必大家也都早有耳闻。相关的各种教程、脚手架也是一抓一大把。而今天博主秉承着删繁就简的思想,记录一下在 Spring Boot 框架下,如何以最快、最简单的方式完成:从数据库逆向工程到持久层、业务层,最后到控制层的实现。(如果想看 SSM 版的整合请移步至:一套带走之:SSM 逆向工程

一、框架

本文中主要用到的框架包括:

  1. Spring Boot
  2. Mybatis
  3. tk.mybatis(通用 Mapper 接口)
  4. PageHelper (分页插件)
  5. Mybatis GeneratorMaven 数据库逆向工程插件)

二、搭建

1、创建 Spring Boot 工程

IDEA 中创建一个 Spring Boot 步骤如下:

  1. 打开 IDEA 后选择 Create New Project

  2. 工程类型选择 Spring Initializr 在右侧 Choose start service URL 选项中选择 DefaultCustom。由于某些原因,Spring 官方的初始化链接有时会异常缓慢,所以博主选择 Custom,来使用阿里的初始化链接。

    https://start.aliyun.com
    
  3. 接下来就是填写项目的基本信息及打包方式,这里大家可根据自己的需求来就好。

  4. 这一步是选择项目依赖,由于我们要搭建的是一个极简的脚手架工程我这里就选择了如下依赖:

    1. Spring Boot DevTools (热部署工具)
    2. Spring Configuration Processor (为程序猿在 application.properties 中配置自定义属性时提供代码补全提示)
    3. Spring Web (提供 Spring MVCTomcat 容器)
    4. Mybatis Framework
    5. MySQL Driver
    6. Junit
    7. 输入工程名称、位置

2、补充依赖

工程基本创建完了,接下来就是添加工程中其他依赖的时候了。完整的 pom 内容如下:

pom.xml

<?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.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.idol</groupId>
    <artifactId>springboot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <mybatis.generator.version>1.3.5</mybatis.generator.version>
    </properties>

    <dependencies>
        <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>2.1.3</version>
        </dependency>
        <!-- 热部署插件:IDEA -->        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!-- Spring Boot application.properties 文件,属性配置提醒 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

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

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

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <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>${mybatis.generator.version}</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>8.0.22</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>4.1.5</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

Tips: 如果你添加了 Spring Boot 的热部署插件,但是没起作用怎么办?别急,按照如下步骤操作,包你好使。

  1. Ctrl+Shift+Alt+/ 后选择 Registry 选项,随后找到compiler.automake.allow.when.app.running 选项,并打上对勾。
  2. 打开 Settings 选择 Build,Execution,Development 选择 Compiler,在后侧面板中勾选 Build project automatically 选项。

3、编写 Mybatis Generator 插件的配置文件

generatorConfig.xml

<?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 标签引入数据库连接配置
        在 jdbcConnection 标签中使用 ${key} 获取。eg:${jdbc.driverClass}
     -->
    <!--<properties resource="jdbc.properties"/>-->

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <!-- 格式化java代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>

        <!-- 增加Models ToStirng方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!-- 增加Models Serializable实现 -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!--增加 tk.Mybatis 插件-->
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <!--让所有 dao 继承自定义的 MyMapper 接口-->
            <property name="mappers" value="tk.mybatis.MyMapper"/>
            <!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true -->
            <property name="caseSensitive" value="true"/>
        </plugin>

        <commentGenerator>
            <!-- 抑制警告 -->
            <property name="suppressTypeWarnings" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
            <!-- 是否生成注释代时间戳 -->
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <!-- 配置数据库连接 -->
        <jdbcConnection
                driverClass="com.mysql.cj.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=UTC"
                userId="root"
                password="root">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>

        <!-- 配置实体类存放路径 -->
        <javaModelGenerator targetPackage="com.idol.pojo" targetProject="src/main/java"/>

        <!-- 配置 XML 存放路径 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>

        <!-- 配置 DAO 存放路径 -->
        <javaClientGenerator
                targetPackage="com.idol.dao"
                targetProject="src/main/java"
                type="XMLMAPPER"/>

        <!-- 配置需要指定生成的数据库和表,当 tableName 的值为 % 时表示生成当前数据库中所有表 -->
        <table tableName="t_people" domainObjectName="People" >
            <!--  可通过 columnOverride 标签,对表中字段所对应的 POJO 属性名进行绑定 -->
            <!--<columnOverride column="sta_evid" property="evid" />-->
        </table>
    </context>
</generatorConfiguration>

Tips:这里需要注意的是,通常情况下这个配置文件的 dtd 文件会因找不到而报红,但这并不影响使用。如果你是一名强迫症患者,那么可进行如下操作,解决报红问题。

  1. 复制报红的 dtd 链接地址至浏览器,下载该文件。

  2. 选择 File ====》 Settings ====》 Languages & FrameworksFile ====》 Schemas and DTDs

  3. IDEA 添加本地 dtd 文件如下图所示

在这里插入图片描述

4、编写 Mapper 接口的父类

编写所有 Mapper 接口的父类,通常情况下我们只需继承 tk.mybatis.mapper.common.Mapper 和对应数据库的接口即可。

MyMapper

package tk.mybatis;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * @author Supreme_Sir
 * @version 1.0
 * @className MyMapper
 * @description 该类不可被 Spring IoC 扫描到
 * @date 2020/11/19 17:18
 **/
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
    
    
}

Tips: 该类一定、一定、一定不可被 Spring IoC 扫描到。

5、生成 POJO 和 Mapper

IDEA 工具条中找到 Mybatis Generator 插件运行项,并双击。如下图所示。

在这里插入图片描述

三、测试

DAO 层完成开发后,我们就可以写测试代码了。

SpringbootDemoApplicationTests

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.idol.dao.PeopleMapper;
import com.idol.pojo.Furniture;
import com.idol.pojo.People;
import com.idol.pojo.Person;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootDemoApplicationTests {
    
    

    @Autowired
    private Person person;
    @Autowired
    private Furniture furniture;
    @Autowired
    private PeopleMapper peopleMapper;

    /**
     * @ConfigurationProperties 注解测试
     */
    @Test
    public void testPerson() {
    
    
        System.out.println(person);
    }

    /**
     * @Value  注解测试
     */
    @Test
    public void testFurniture() {
    
    
        System.out.println(furniture);
    }

    /**
     * 测试 tk.mybatis 和 PageHelper 功能
     */
    @Test
    public void testPeopleMapper(){
    
    
        // 每页显示一条数据,查询第二页的内容
        PageHelper.startPage(2, 1);
        PageInfo<People> peoplePageInfo = new PageInfo<>(peopleMapper.selectAll());
        for (People p : peoplePageInfo.getList()) {
    
    
            System.out.println(p);
        }
    }
}

Tips:运行测试前,一定要在 *Application 类上添加 @MapperScan 注解。代码如下

SpringbootDemoApplication

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("com.idol.dao")
public class SpringbootDemoApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }

}

Tips:这里需要注意的是,SpringbootDemoApplication 需要放置位置会决定项目扫描的包。即,Spring Boot 默认会扫描 SpringbootDemoApplication 类所在包的子包,进行 IoC 初始化。所以通用接口 MyMapper 对象必须放在 SpringbootDemoApplication 类所在包的上级包中。

四、补充

细心的同学可能会发现,我在测试代码中有两个“多余”的测试。而那两个测试虽然简单,其中蕴含的原理还是有一二的。

  1. 同时存在 application.propertiesapplication.yml 配置文件的情况下,properties 文件优先级更高。
  2. 展示如何通过配置文件为数组、列表、复杂对象等赋值
  3. 展示如何通过 @Value 注解赋值
  4. 使用 @ConfigurationProperties 注解赋值时,该对象的属性是必须具有 SetterGetter 方法的。

源码

源码下载

附:

PageHelper GitHub
PageHelper 官网
通用 Mapper3 GitHub
通用 Mapper4 码云

----------------------------- 我知道我想要的,绝不仅此而已。------------------------------

猜你喜欢

转载自blog.csdn.net/Supreme_Sir/article/details/109831066