Mybatis逆向工程封装、通用Mapper、Spring Boot

新建Module

在这里插入图片描述
如图蓝色字体所示,选择Spring Initializer,点击next
在这里插入图片描述
这里Group 和 Artifact自己看情况写,如果嫌麻烦,可以按照我的来写。
在这里插入图片描述
配置好之后点击next

在这里插入图片描述
这里我选择web里面的spring web省的配置项目里面Spring Boot的基础环境。也可以不选择直接next,手动新建。

在这里插入图片描述
直接点击finish即可完成工程创建。

文件源码

修改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.1.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.njust</groupId>
    <artifactId>encapsulation</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>encapsulation</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--引入SpringBoot起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--alibaba连接池 druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!--引入fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <!--引入数据库连接驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <!--mybatis-start-->
        <!--引入mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--引入 mybatis-generator-core 才能使用逆向工程-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <!--mapper 引入可以使用通用mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!--pagehelper 引入分页插件依赖的jar包-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!--日志-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
            <version>1.3.3.RELEASE</version>
        </dependency>
    </dependencies>
    <!--2.引入插件-->
    <build>
        <plugins>
            <!--maven插件-->
            <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.2</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.29</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>4.0.0</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

重命名application.propertiesapplication.yml
在这里插入图片描述
在这里插入图片描述
新建基类Mapper
在这里插入图片描述
源代码如下:

package com.njust.encapsulation.utils;

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

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/22 9:12
 * @description:
 */
public interface IBaseMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

application.yml


server:
  port: 8080

logging:
  config: classpath:log4j.properties
  level:
    dao: debug
    org:
      mybatis: debug
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8

  jackson:
    default-property-inclusion: non_null

# 指定数据库中表生成实体的路径
mybatis:
  type-aliases-package: com.example.demo.entity
  mapper-locations: classpath:mappers/*.xml
  configuration:
#    输出sql日志信息
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 对应utils目录下的IBaseMapper模板Mapper
mapper:
  mappers:
  - com.njust.encapsulation.utils.IBaseMapper
  not-empty: false
  identity: MYSQL


#pagehelper
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params:
    count: countSql


在项目中配置好Log4j配置文件,便于以后调试。
在这里插入图片描述
log4j.properties

#Console Log
log4j.rootLogger=INFO,console,debug,info,warn,error

LOG_PATTERN=[%d{yyyy-MM-dd HH:mm:ss.SSS}] boot%X{context} - %5p [%t] --- %c{1}: %m%n

#A1--Print log to Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.Threshold=INFO
log4j.appender.info.File=${LOG_PATH}/${LOG_FILE}_info.log
log4j.appender.info.DatePattern='.'yyyy-MM-dd
log4j.appender.info.layout = org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.Threshold=ERROR
log4j.appender.error.File=${LOG_PATH}/${LOG_FILE}_error.log
log4j.appender.error.DatePattern='.'yyyy-MM-dd
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=${LOG_PATTERN}


log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.File=${LOG_PATH}/${LOG_FILE}_debug.log
log4j.appender.debug.DatePattern='.'yyyy-MM-dd
log4j.appender.debug.layout = org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.warn.Threshold=WARN
log4j.appender.warn.File=${LOG_PATH}/${LOG_FILE}_warn.log
log4j.appender.warn.DatePattern='.'yyyy-MM-dd
log4j.appender.warn.layout = org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern=${LOG_PATTERN}

新建generatorConfig.xml,配置mybatis逆向工程文件。
在这里插入图片描述
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>
    <!--导入属性配置-->
    <!--1.jdbcConnection设置数据库连接-->
    <!--2.javaModelGenerator设置类的生成位置-->
    <!--3.sqlMapGenerator设置生成xml的位置-->
    <!--4.javaClientGenerator设置生成dao层接口的位置-->
    <!--5.table设置要进行逆向工程的表名以及要生成的实体类的名称-->
    <!--指定特定数据库的jdbc驱动jar包的位置-->

    <context id="default" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.chen.common.utils.IBaseMapper"/>
        </plugin>

        <!-- 配置生成pojo的序列化的插件,mybatis支持很多插件,这些插件都在 org.mybatis.generator.plugins包下  -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

        <!-- 配置生成pojo的toString()方法的插件,mybatis支持很多插件,这些插件都在 org.mybatis.generator.plugins包下 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />

        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接 -->
        <jdbcConnection
                driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=UTF-8"
                userId="root"
                password="root">
        </jdbcConnection>


        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <javaModelGenerator targetPackage="com.njust.encapsulation.entity" targetProject="./src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->

        <!-- targetPackage:mapper接口dao生成的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.njust.encapsulation.mapper" targetProject="./src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <table tableName="user">
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

生成逆向工程代码

在这里插入图片描述
双击运行mybatis-generator:generate即可。控制台输出信息如下:

[INFO] Scanning for projects...
[INFO] 
[INFO] ----------------------< com.njust:encapsulation >-----------------------
[INFO] Building encapsulation 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ encapsulation ---
[INFO] Connecting to the Database
[INFO] Introspecting table user
log4j:WARN No appenders could be found for logger (org.mybatis.generator.internal.db.DatabaseIntrospector).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[INFO] Generating Record class for table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map for table user
[INFO] Saving file UserMapper.xml
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.647 s
[INFO] Finished at: 2020-03-22T21:24:42+08:00
[INFO] ------------------------------------------------------------------------
[WARNING] The requested profile "nexus" could not be activated because it does not exist.

Process finished with exit code 0


可以看到我们已经成功生成了我们需要的代码。
在这里插入图片描述
例如user的源代码是:

package com.njust.encapsulation.entity;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;

public class User implements Serializable {
    /**
     * 用户id
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    /**
     * 用户名
     */
    @Column(name = "user_name")
    private String userName;

    /**
     * 密码
     */
    private String password;

    /**
     * 创建时间
     */
    @Column(name = "create_time")
    private Date createTime;

    private static final long serialVersionUID = 1L;

    public User(Integer id, String userName, String password, Date createTime) {
        this.id = id;
        this.userName = userName;
        this.password = password;
        this.createTime = createTime;
    }

    public User() {
        super();
    }

    /**
     * 获取用户id
     *
     * @return id - 用户id
     */
    public Integer getId() {
        return id;
    }

    /**
     * 设置用户id
     *
     * @param id 用户id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 获取用户名
     *
     * @return user_name - 用户名
     */
    public String getUserName() {
        return userName;
    }

    /**
     * 设置用户名
     *
     * @param userName 用户名
     */
    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    /**
     * 获取密码
     *
     * @return password - 密码
     */
    public String getPassword() {
        return password;
    }

    /**
     * 设置密码
     *
     * @param password 密码
     */
    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    /**
     * 获取创建时间
     *
     * @return create_time - 创建时间
     */
    public Date getCreateTime() {
        return createTime;
    }

    /**
     * 设置创建时间
     *
     * @param createTime 创建时间
     */
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", userName=").append(userName);
        sb.append(", password=").append(password);
        sb.append(", createTime=").append(createTime);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

其他代码读者可以自行运行查看,这里不再展示。

测试

新建service包,并实现基本service的查询。
在这里插入图片描述
UserService

package com.njust.encapsulation.service;

import com.njust.encapsulation.entity.User;

import java.util.List;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/22 21:28
 * @description:
 */
public interface UserService {
    public List<User> selectByPage(Integer page, User user);

}

UserServiceImpl

package com.njust.encapsulation.service.impl;

import com.github.pagehelper.PageHelper;
import com.mysql.jdbc.StringUtils;
import com.njust.encapsulation.entity.User;
import com.njust.encapsulation.mapper.UserMapper;
import com.njust.encapsulation.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/22 21:28
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据名称模糊分页查询。
     * @param page
     * @param user
     * @return
     */
    @Override
    public List<User> selectByPage(Integer page, User user) {
        PageHelper.startPage(page, 5);
        // 告诉系统查询那个类
        Example example = new Example(user.getClass());
        // 创建查询
        Example.Criteria criteria = example.createCriteria();
        // 模糊查询的判断
        if (!StringUtils.isEmptyOrWhitespaceOnly(user.getUserName())) {
            criteria.andLike("userName", "%" + user.getUserName() + "%");
        }
        example.orderBy("password").desc();
        return userMapper.selectByExample(example);
    }
}

选中类,按住ctrl+shift+T。生成测试类。
在这里插入图片描述
生成UserServiceImplTest,源代码如下:

package com.njust.encapsulation.service.impl;

import com.njust.encapsulation.entity.User;
import com.njust.encapsulation.service.UserService;
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.context.junit4.SpringRunner;

import static org.junit.Assert.*;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/22 21:38
 * @description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {

    @Autowired
    private UserService userService;

    @Test
    public void selectByPage() {
        User user = new User();
        user.setUserName("jackchen");

        userService.selectByPage(1, user).forEach(System.out::println);

    }
}

运行结果:

[2020-03-22 21:50:07.628] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.njust.encapsulation.service.impl.UserServiceImplTest], using SpringBootContextLoader
[2020-03-22 21:50:07.637] boot -  INFO [main] --- AbstractContextLoader: Could not detect default resource locations for test class [com.njust.encapsulation.service.impl.UserServiceImplTest]: no resource found for suffixes {-context.xml, Context.groovy}.
[2020-03-22 21:50:07.639] boot -  INFO [main] --- AnnotationConfigContextLoaderUtils: Could not detect default configuration classes for test class [com.njust.encapsulation.service.impl.UserServiceImplTest]: UserServiceImplTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
[2020-03-22 21:50:07.868] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Found @SpringBootConfiguration com.njust.encapsulation.EncapsulationApplication for test class com.njust.encapsulation.service.impl.UserServiceImplTest
[2020-03-22 21:50:08.043] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
[2020-03-22 21:50:08.078] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@c267ef4, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@30ee2816, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@31d7b7bf, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@635eaaf1, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5c30a9b0, org.springframework.test.context.transaction.TransactionalTestExecutionListener@1ddf84b8, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@1139b2f3, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@7a69b07, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@5e82df6a, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@3f197a46, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@636be97c, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@50a638b5][2020-03-22 21:50:08.308] boot -  INFO [background-preinit] --- Version: HV000001: Hibernate Validator 6.0.18.Final

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.1.10.RELEASE)

[2020-03-22 21:50:09.513] boot -  INFO [main] --- UserServiceImplTest: Starting UserServiceImplTest on root-PC with PID 9968 (started by Administrator in D:\nanligong\mianshi\project\easy_code\encapsulation)
[2020-03-22 21:50:09.566] boot -  INFO [main] --- UserServiceImplTest: No active profile set, falling back to default profiles: default
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
[2020-03-22 21:50:13.163] boot -  INFO [main] --- DruidDataSourceAutoConfigure: Init DruidDataSource
[2020-03-22 21:50:13.459] boot -  INFO [main] --- DruidDataSource: {dataSource-1} inited
Using VFS adapter tk.mybatis.mapper.autoconfigure.SpringBootVFS
Scanned package: 'com.example.demo.entity' for aliases
Parsed mapper file: 'file [D:\nanligong\mianshi\project\easy_code\encapsulation\target\classes\mappers\UserMapper.xml]'
[2020-03-22 21:50:14.872] boot -  INFO [main] --- ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor'
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
[2020-03-22 21:50:15.628] boot -  INFO [main] --- UserServiceImplTest: Started UserServiceImplTest in 7.468 seconds (JVM running for 8.91)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6ede46f6] was not registered for synchronization because synchronization is not active
Cache Hit Ratio [SQL_CACHE]: 0.0
Sun Mar 22 21:50:16 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@378cfecf] will not be managed by Spring
==>  Preparing: SELECT count(0) FROM user WHERE (user_name LIKE ?) 
==> Parameters: %jackchen%(String)
<==    Columns: count(0)
<==        Row: 1
<==      Total: 1
==>  Preparing: SELECT id,user_name,password,create_time FROM user WHERE ( user_name like ? ) order by password DESC LIMIT ? 
==> Parameters: %jackchen%(String), 5(Integer)
<==    Columns: id, user_name, password, create_time
<==        Row: 2, jackchen, 123456, 2019-04-07 19:03:48.0
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6ede46f6]
User [Hash = 1109966680, id=2, userName=jackchen, password=123456, createTime=Sun Apr 07 19:03:48 CST 2019, serialVersionUID=1]
[2020-03-22 21:50:16.679] boot -  INFO [Thread-2] --- ThreadPoolTaskExecutor: Shutting down ExecutorService 'applicationTaskExecutor'
[2020-03-22 21:50:16.688] boot -  INFO [Thread-2] --- DruidDataSource: {dataSource-1} closed
Process finished with exit code 0

但是每一个类都写一个Mapper是不是代码重复了呢?

封装

新建通用类Share
在这里插入图片描述
Share

package com.njust.encapsulation.usual;

import com.github.pagehelper.PageHelper;
import com.njust.encapsulation.utils.IBaseMapper;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/22 20:09
 * @description:
 */
public class Share {

    public static final Integer DEFAULT_PAGE_SIZE = 10;

    public static <T> List<T> selectByPage(Integer page, T t, IBaseMapper<T> baseMapper) {
        PageHelper.startPage(page, DEFAULT_PAGE_SIZE);
        // 告诉系统查询那个类
        Example example = new Example(t.getClass());
        // 创建查询
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo(t);

        return baseMapper.selectByExample(example);
    }
}

在UserServiceImpl中新增通用查询方法
UserServiceImpl

package com.njust.encapsulation.service.impl;

import com.github.pagehelper.PageHelper;
import com.mysql.jdbc.StringUtils;
import com.njust.encapsulation.entity.User;
import com.njust.encapsulation.mapper.UserMapper;
import com.njust.encapsulation.service.UserService;
import com.njust.encapsulation.usual.Share;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/22 21:28
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据名称模糊分页查询。
     * @param page
     * @param user
     * @return
     */
    @Override
    public List<User> selectByPage(Integer page, User user) {
        PageHelper.startPage(page, 5);
        // 告诉系统查询那个类
        Example example = new Example(user.getClass());
        // 创建查询
        Example.Criteria criteria = example.createCriteria();
        // 模糊查询的判断
        if (!StringUtils.isEmptyOrWhitespaceOnly(user.getUserName())) {
            criteria.andLike("userName", "%" + user.getUserName() + "%");
        }
        example.orderBy("password").desc();
        return userMapper.selectByExample(example);
    }

    @Override
    public List<User> selectByPageCom(Integer page, User user) {
        List<User> users = Share.selectByPage(page, user, userMapper);
        return users;
    }
}

UserServiceImplTest

package com.njust.encapsulation.service.impl;

import com.njust.encapsulation.entity.User;
import com.njust.encapsulation.service.UserService;
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.context.junit4.SpringRunner;

import static org.junit.Assert.*;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/22 21:38
 * @description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {

    @Autowired
    private UserService userService;

    @Test
    public void selectByPage() {
        User user = new User();
        user.setUserName("jackchen");

        userService.selectByPage(1, user).forEach(System.out::println);

    }

    @Test
    public void selectByPage2() {
        User user = new User();
        user.setUserName("jackchen");

        userService.selectByPageCom(1, user).forEach(System.out::println);

    }
}

结果输出:


[2020-03-23 00:08:22.882] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.njust.encapsulation.service.impl.UserServiceImplTest], using SpringBootContextLoader
[2020-03-23 00:08:22.894] boot -  INFO [main] --- AbstractContextLoader: Could not detect default resource locations for test class [com.njust.encapsulation.service.impl.UserServiceImplTest]: no resource found for suffixes {-context.xml, Context.groovy}.
[2020-03-23 00:08:22.896] boot -  INFO [main] --- AnnotationConfigContextLoaderUtils: Could not detect default configuration classes for test class [com.njust.encapsulation.service.impl.UserServiceImplTest]: UserServiceImplTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
[2020-03-23 00:08:23.155] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Found @SpringBootConfiguration com.njust.encapsulation.EncapsulationApplication for test class com.njust.encapsulation.service.impl.UserServiceImplTest
[2020-03-23 00:08:23.327] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
[2020-03-23 00:08:23.359] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@30ee2816, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@31d7b7bf, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@635eaaf1, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@5c30a9b0, org.springframework.test.context.support.DirtiesContextTestExecutionListener@1ddf84b8, org.springframework.test.context.transaction.TransactionalTestExecutionListener@1139b2f3, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@7a69b07, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@5e82df6a, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@3f197a46, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@636be97c, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@50a638b5, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@1817d444][2020-03-23 00:08:23.658] boot -  INFO [background-preinit] --- Version: HV000001: Hibernate Validator 6.0.18.Final

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.1.10.RELEASE)

[2020-03-23 00:08:24.948] boot -  INFO [main] --- UserServiceImplTest: Starting UserServiceImplTest on root-PC with PID 10076 (started by Administrator in D:\nanligong\mianshi\project\easy_code\encapsulation)
[2020-03-23 00:08:24.949] boot -  INFO [main] --- UserServiceImplTest: No active profile set, falling back to default profiles: default
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
[2020-03-23 00:08:29.717] boot -  INFO [main] --- DruidDataSourceAutoConfigure: Init DruidDataSource
[2020-03-23 00:08:30.357] boot -  INFO [main] --- DruidDataSource: {dataSource-1} inited
Using VFS adapter tk.mybatis.mapper.autoconfigure.SpringBootVFS
Scanned package: 'com.example.demo.entity' for aliases
Parsed mapper file: 'file [D:\nanligong\mianshi\project\easy_code\encapsulation\target\classes\mappers\UserMapper.xml]'
[2020-03-23 00:08:32.665] boot -  INFO [main] --- ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor'
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
[2020-03-23 00:08:33.767] boot -  INFO [main] --- UserServiceImplTest: Started UserServiceImplTest in 10.316 seconds (JVM running for 12.006)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@210308d5] was not registered for synchronization because synchronization is not active
Cache Hit Ratio [SQL_CACHE]: 0.0
Mon Mar 23 00:08:35 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@27d33393] will not be managed by Spring
==>  Preparing: SELECT count(0) FROM user WHERE (user_name = ?) 
==> Parameters: jackchen(String)
<==    Columns: count(0)
<==        Row: 1
<==      Total: 1
==>  Preparing: SELECT id,user_name,password,create_time FROM user WHERE ( user_name = ? ) LIMIT ? 
==> Parameters: jackchen(String), 10(Integer)
<==    Columns: id, user_name, password, create_time
<==        Row: 2, jackchen, 123456, 2019-04-07 19:03:48.0
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@210308d5]
User [Hash = 21331934, id=2, userName=jackchen, password=123456, createTime=Sun Apr 07 19:03:48 CST 2019, serialVersionUID=1]
[2020-03-23 00:08:35.484] boot -  INFO [Thread-2] --- ThreadPoolTaskExecutor: Shutting down ExecutorService 'applicationTaskExecutor'
[2020-03-23 00:08:35.491] boot -  INFO [Thread-2] --- DruidDataSource: {dataSource-1} closed

Process finished with exit code 0

修改 generatorConfig.xml按照上面的步骤生成sys_log的逆向工程代码
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>
    <!--导入属性配置-->
    <!--1.jdbcConnection设置数据库连接-->
    <!--2.javaModelGenerator设置类的生成位置-->
    <!--3.sqlMapGenerator设置生成xml的位置-->
    <!--4.javaClientGenerator设置生成dao层接口的位置-->
    <!--5.table设置要进行逆向工程的表名以及要生成的实体类的名称-->
    <!--指定特定数据库的jdbc驱动jar包的位置-->

    <context id="default" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.njust.encapsulation.utils.IBaseMapper"/>
        </plugin>

        <!-- 配置生成pojo的序列化的插件,mybatis支持很多插件,这些插件都在 org.mybatis.generator.plugins包下  -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

        <!-- 配置生成pojo的toString()方法的插件,mybatis支持很多插件,这些插件都在 org.mybatis.generator.plugins包下 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />

        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接 -->
        <jdbcConnection
                driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=UTF-8"
                userId="root"
                password="root">
        </jdbcConnection>


        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <javaModelGenerator targetPackage="com.njust.encapsulation.entity" targetProject="./src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->

        <!-- targetPackage:mapper接口dao生成的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.njust.encapsulation.mapper" targetProject="./src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!--<table tableName="user">-->
            <!--<generatedKey column="id" sqlStatement="Mysql" identity="true"/>-->
        <!--</table>-->
        <table tableName="sys_log">
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

新建SysLogServiceImpl,代码结构为:
在这里插入图片描述
SysLogServiceImpl

package com.njust.encapsulation.service.impl;

import com.njust.encapsulation.entity.SysLog;
import com.njust.encapsulation.mapper.SysLogMapper;
import com.njust.encapsulation.service.SysLogService;
import com.njust.encapsulation.usual.Share;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/23 0:17
 * @description:
 */
@Service
public class SysLogServiceImpl implements SysLogService {
    @Autowired
    private SysLogMapper sysLogMapper;

    @Override
    public List<SysLog> selectByPageCom(Integer page, SysLog sysLog) {
        return Share.selectByPage(page, sysLog, sysLogMapper);
    }
}

SysLogService

package com.njust.encapsulation.service;

import com.njust.encapsulation.entity.SysLog;
import com.njust.encapsulation.entity.User;

import java.util.List;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/22 21:28
 * @description:
 */
public interface SysLogService {

    List<SysLog> selectByPageCom(Integer page, SysLog sysLog);
}

SysLogServiceImplTest

package com.njust.encapsulation.service.impl;
import java.util.Date;

import com.njust.encapsulation.entity.SysLog;
import com.njust.encapsulation.service.SysLogService;
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.context.junit4.SpringRunner;

import static org.junit.Assert.*;

/**
 * @author Chen
 * @version 1.0
 * @date 2020/3/23 0:19
 * @description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SysLogServiceImplTest {
    @Autowired
    private SysLogService sysLogService;

    @Test
    public void selectByPageCom() {
        SysLog sysLog = new SysLog();
        sysLog.setUserId(90001);
        sysLogService.selectByPageCom(1, sysLog).forEach(System.out::println);


    }
}

输出:

[2020-03-23 00:21:07.199] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.njust.encapsulation.service.impl.SysLogServiceImplTest], using SpringBootContextLoader
[2020-03-23 00:21:07.210] boot -  INFO [main] --- AbstractContextLoader: Could not detect default resource locations for test class [com.njust.encapsulation.service.impl.SysLogServiceImplTest]: no resource found for suffixes {-context.xml, Context.groovy}.
[2020-03-23 00:21:07.211] boot -  INFO [main] --- AnnotationConfigContextLoaderUtils: Could not detect default configuration classes for test class [com.njust.encapsulation.service.impl.SysLogServiceImplTest]: SysLogServiceImplTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
[2020-03-23 00:21:07.517] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Found @SpringBootConfiguration com.njust.encapsulation.EncapsulationApplication for test class com.njust.encapsulation.service.impl.SysLogServiceImplTest
[2020-03-23 00:21:07.684] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
[2020-03-23 00:21:07.714] boot -  INFO [main] --- SpringBootTestContextBootstrapper: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@31d7b7bf, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@635eaaf1, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@5c30a9b0, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@1ddf84b8, org.springframework.test.context.support.DirtiesContextTestExecutionListener@1139b2f3, org.springframework.test.context.transaction.TransactionalTestExecutionListener@7a69b07, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@5e82df6a, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@3f197a46, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@636be97c, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@50a638b5, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@1817d444, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@6ca8564a][2020-03-23 00:21:07.959] boot -  INFO [background-preinit] --- Version: HV000001: Hibernate Validator 6.0.18.Final

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.1.10.RELEASE)

[2020-03-23 00:21:08.918] boot -  INFO [main] --- SysLogServiceImplTest: Starting SysLogServiceImplTest on root-PC with PID 9640 (started by Administrator in D:\nanligong\mianshi\project\easy_code\encapsulation)
[2020-03-23 00:21:08.919] boot -  INFO [main] --- SysLogServiceImplTest: No active profile set, falling back to default profiles: default
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
[2020-03-23 00:21:11.963] boot -  INFO [main] --- DruidDataSourceAutoConfigure: Init DruidDataSource
[2020-03-23 00:21:12.278] boot -  INFO [main] --- DruidDataSource: {dataSource-1} inited
Using VFS adapter tk.mybatis.mapper.autoconfigure.SpringBootVFS
Scanned package: 'com.example.demo.entity' for aliases
Parsed mapper file: 'file [D:\nanligong\mianshi\project\easy_code\encapsulation\target\classes\mappers\SysLogMapper.xml]'
Parsed mapper file: 'file [D:\nanligong\mianshi\project\easy_code\encapsulation\target\classes\mappers\UserMapper.xml]'
[2020-03-23 00:21:13.818] boot -  INFO [main] --- ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor'
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
[2020-03-23 00:21:14.622] boot -  INFO [main] --- SysLogServiceImplTest: Started SysLogServiceImplTest in 6.819 seconds (JVM running for 8.341)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1229a2b7] was not registered for synchronization because synchronization is not active
Cache Hit Ratio [SQL_CACHE]: 0.0
Mon Mar 23 00:21:15 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@762637be] will not be managed by Spring
==>  Preparing: SELECT count(0) FROM sys_log WHERE (user_id = ?) 
==> Parameters: 90001(Integer)
<==    Columns: count(0)
<==        Row: 1
<==      Total: 1
==>  Preparing: SELECT id,user_id,module,data,memo,create_time FROM sys_log WHERE ( user_id = ? ) LIMIT ? 
==> Parameters: 90001(Integer), 10(Integer)
<==    Columns: id, user_id, module, data, memo, create_time
<==        Row: 8, 90001, 用户登录模块, {"userName":"a-xiu-luo","password":"123456","userId":90001}, 用户登录成功记录相关登录信息, 2020-03-18 13:10:41.0
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1229a2b7]
SysLog [Hash = 1154481189, id=8, userId=90001, module=用户登录模块, data={"userName":"a-xiu-luo","password":"123456","userId":90001}, memo=用户登录成功记录相关登录信息, createTime=Wed Mar 18 13:10:41 CST 2020, serialVersionUID=1]
[2020-03-23 00:21:15.812] boot -  INFO [Thread-2] --- ThreadPoolTaskExecutor: Shutting down ExecutorService 'applicationTaskExecutor'
[2020-03-23 00:21:15.821] boot -  INFO [Thread-2] --- DruidDataSource: {dataSource-1} closed

Process finished with exit code 0

使用通用模板同样开源输出。

总结

遇到重复的代码我们需要重构。感谢所有开源的人!

发布了22 篇原创文章 · 获赞 4 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/qq_32510597/article/details/105035132