spring boot中使用mybatis的通用mapper以及genarator (一)

版权声明:转载请注明原创 https://blog.csdn.net/qq_42151769/article/details/89914737

这个博客介绍在spring boot项目中使用genarator生成mybatis代码,并且配合使用通用mapper

在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 http://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.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hf</groupId>
    <artifactId>common-mapper</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>common-mapper</name>
    <description>mybatis通用mapper使用</description>

    <properties>
        <java.version>1.8</java.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.0.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--common mapper dependency start-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!--common mapper dependency end-->

        <!--pagehelper 分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--pagehelper 分页插件-->

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>


            <!--自动生成mybatis 插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <!-- 指定插件运行的generator.xml文件位置-->
                    <configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <!-- 允许移动生成的文件-->
                    <verbose>true</verbose>
                    <!-- 允许覆盖生成的文件-->
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                    <!--如果在genaratorConfig.xml配置了TKmybatis配置 通用插件的配置,需要在这里指定tk插件的版本,版本和上面引入的依赖一样-->
                    <!--在genaratorConfig.xm配置TK插件,能在生成实体类的时候,字段生成注解如:@Id,这是为通用mapper使用的-->
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper-spring-boot-starter</artifactId>
                        <version>1.2.4</version>
                    </dependency>
                </dependencies>
            </plugin>
            <!--自动生成mybatis插件-->

        </plugins>
    </build>

</project>

特别需要注意插件的配置,截取插件的配置如下:

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>


            <!--自动生成mybatis 插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <!-- 指定插件运行的generator.xml文件位置-->
                    <configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <!-- 允许移动生成的文件-->
                    <verbose>true</verbose>
                    <!-- 允许覆盖生成的文件-->
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                    <!--如果在genaratorConfig.xml配置了TKmybatis配置 通用插件的配置,需要在这里指定tk插件的版本,版本和上面引入的依赖一样-->
                    <!--在genaratorConfig.xm配置TK插件,能在生成实体类的时候,字段生成注解如:@Id,这是为通用mapper使用的-->
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper-spring-boot-starter</artifactId>
                        <version>1.2.4</version>
                    </dependency>
                </dependencies>
            </plugin>
            <!--自动生成mybatis插件-->

        </plugins>
    </build>

需要注意点:

1.指定插件的位置:如下截图

实际存放的位置如下:

2.需要在插件中增加tk的依赖,如下:

原因是在generatorConfig.xml中配置了如下:

下面是generatorConfig.xml的配置

关于generatorConfig.xml的具体配置,已经每个配置的含义,可以查看文档:

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>
    <!--数据库驱动jar -->
    <classPathEntry location="D:\desoft\maven\repository\mysql\mysql-connector-java\5.1.17\mysql-connector-java-5.1.17.jar" />

    <context id="Tables" targetRuntime="MyBatis3">


       <!-- 通用mapper插件配置 -->
        <!--在genaratorConfig.xm配置TK插件,能在生成实体类的时候,字段生成注解如:@Id,这是为通用mapper使用的-->
        <property name="javaFileEncoding" value="UTF-8"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <!--注意这里需要预先指定写好的通用mapper接口,自动生成的接口全部继承这个接口,并且在扫描mapper的时候,这个类不能被扫描到的-->
            <property name="mappers" value="com.hf.commonmapper.common.BaseMapper"/>
        </plugin>
        <!-- 通用mapper插件配置 -->

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

        <!--数据库连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ccclubs_t3" userId="root"
                        password="root">
        </jdbcConnection>
        <!--默认false Java type resolver will always use java.math.BigDecimal if
            the database column is of type DECIMAL or NUMERIC. -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建 使用Maven生成在target目录下,会自动创建) -->
        <javaModelGenerator targetPackage="com.hf.commonmapper.model"
                            targetProject="D:\ideawks\common-mapper\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--生成mapper.xml文件路径 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject="D:\ideawks\common-mapper\src\main\java">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!--生成mapper接口文件 可以配置 type="XMLMAPPER"生成xml的dao实现 context id="DB2Tables" 修改targetRuntime="MyBatis3" -->
        <!--targetProject指定项目的路径,可以是相对路径,到java目录位置-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.hf.commonmapper.mapper"
                             targetProject="D:\ideawks\common-mapper\src\main\java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!--对应数据库表 mysql可以加入主键自增 字段命名 忽略某字段等,这个只能配置单表,配置几张表就需要几个这个配置项 -->
      <!--  <table tableName="t_system_city" domainObjectName="TsystemCity" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />-->

        <!--如果需要生成改数据库中所有的表的话,用如下的配置-->
        <table tableName="%" />


    </context>
</generatorConfiguration>

需要注意点:

1.配置通用mapper插件,为了生存的实体类中含有注解(因为通用mapper必须使用有注解的实体类)

如下:

图中指定了通用mapper所在接口,如下图:

需要先写好这个接口,如下:  可以看到其实就是一个空接口

package com.hf.commonmapper.common;

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

/**
 * @Description:
 * @Date: 2019/5/7
 * @Auther: 
 */
public interface BaseMapper<T>{
}

2.如果需要生成指定数据库的所有表的话,用下面的配置

<table>这里用的通配符匹配全部的表,另外所有表都有自动增长的id字段。如果不是所有表的配置都一样,可以做针对性的配置。 如下

<table tableName="%">
			<generatedKey column="id" sqlStatement="Mysql"/>
		</table>

配置好了之后,直接运行插件:

可以看到执行成功了:

查看实体类和mapper以及xml

如下图,实体类已经全部生成,并且带上了我们需要的注解

生成的mapper接口如下:

可以看到每个mapper都自动有一些方法了,并且都继承了自定义的通用Mapper BaseMapper这个接口

我们在来看看生成的xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hf.commonmapper.mapper.SpvScheduleLogMapper" >
  <resultMap id="BaseResultMap" type="com.hf.commonmapper.model.SpvScheduleLog" >
    <!--
      WARNING - @mbg.generated
    -->
    <id column="uuid" property="uuid" jdbcType="CHAR" />
    <result column="created_on" property="createdOn" jdbcType="TIMESTAMP" />
    <result column="created_by" property="createdBy" jdbcType="CHAR" />
    <result column="updated_on" property="updatedOn" jdbcType="TIMESTAMP" />
    <result column="updated_by" property="updatedBy" jdbcType="CHAR" />
    <result column="version" property="version" jdbcType="INTEGER" />
    <result column="group_code" property="groupCode" jdbcType="VARCHAR" />
    <result column="batch_no" property="batchNo" jdbcType="VARCHAR" />
    <result column="batch_result" property="batchResult" jdbcType="VARCHAR" />
    <result column="main_uuid" property="mainUuid" jdbcType="CHAR" />
    <result column="main_table" property="mainTable" jdbcType="VARCHAR" />
    <result column="schedule_name" property="scheduleName" jdbcType="VARCHAR" />
    <result column="schedule_description" property="scheduleDescription" jdbcType="VARCHAR" />
    <result column="schedule_sql" property="scheduleSql" jdbcType="VARCHAR" />
    <result column="params_str" property="paramsStr" jdbcType="OTHER" />
    <result column="interface_url" property="interfaceUrl" jdbcType="VARCHAR" />
    <result column="interface_result" property="interfaceResult" jdbcType="VARCHAR" />
    <result column="retry_count" property="retryCount" jdbcType="INTEGER" />
    <result column="status" property="status" jdbcType="INTEGER" />
    <result column="request_time" property="requestTime" jdbcType="TIMESTAMP" />
    <result column="response_time" property="responseTime" jdbcType="TIMESTAMP" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <!--
      WARNING - @mbg.generated
    -->
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <!--
      WARNING - @mbg.generated
    -->
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    <!--
      WARNING - @mbg.generated
    -->
    uuid, created_on, created_by, updated_on, updated_by, version, group_code, batch_no, 
    batch_result, main_uuid, main_table, schedule_name, schedule_description, schedule_sql, 
    params_str, interface_url, interface_result, retry_count, status, request_time, response_time
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.hf.commonmapper.model.SpvScheduleLogExample" >
    <!--
      WARNING - @mbg.generated
    -->
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from spv_schedule_log
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <delete id="deleteByExample" parameterType="com.hf.commonmapper.model.SpvScheduleLogExample" >
    <!--
      WARNING - @mbg.generated
    -->
    delete from spv_schedule_log
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <select id="countByExample" parameterType="com.hf.commonmapper.model.SpvScheduleLogExample" resultType="java.lang.Integer" >
    <!--
      WARNING - @mbg.generated
    -->
    select count(*) from spv_schedule_log
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    <!--
      WARNING - @mbg.generated
    -->
    update spv_schedule_log
    <set >
      <if test="record.uuid != null" >
        uuid = #{record.uuid,jdbcType=CHAR},
      </if>
      <if test="record.createdOn != null" >
        created_on = #{record.createdOn,jdbcType=TIMESTAMP},
      </if>
      <if test="record.createdBy != null" >
        created_by = #{record.createdBy,jdbcType=CHAR},
      </if>
      <if test="record.updatedOn != null" >
        updated_on = #{record.updatedOn,jdbcType=TIMESTAMP},
      </if>
      <if test="record.updatedBy != null" >
        updated_by = #{record.updatedBy,jdbcType=CHAR},
      </if>
      <if test="record.version != null" >
        version = #{record.version,jdbcType=INTEGER},
      </if>
      <if test="record.groupCode != null" >
        group_code = #{record.groupCode,jdbcType=VARCHAR},
      </if>
      <if test="record.batchNo != null" >
        batch_no = #{record.batchNo,jdbcType=VARCHAR},
      </if>
      <if test="record.batchResult != null" >
        batch_result = #{record.batchResult,jdbcType=VARCHAR},
      </if>
      <if test="record.mainUuid != null" >
        main_uuid = #{record.mainUuid,jdbcType=CHAR},
      </if>
      <if test="record.mainTable != null" >
        main_table = #{record.mainTable,jdbcType=VARCHAR},
      </if>
      <if test="record.scheduleName != null" >
        schedule_name = #{record.scheduleName,jdbcType=VARCHAR},
      </if>
      <if test="record.scheduleDescription != null" >
        schedule_description = #{record.scheduleDescription,jdbcType=VARCHAR},
      </if>
      <if test="record.scheduleSql != null" >
        schedule_sql = #{record.scheduleSql,jdbcType=VARCHAR},
      </if>
      <if test="record.paramsStr != null" >
        params_str = #{record.paramsStr,jdbcType=OTHER},
      </if>
      <if test="record.interfaceUrl != null" >
        interface_url = #{record.interfaceUrl,jdbcType=VARCHAR},
      </if>
      <if test="record.interfaceResult != null" >
        interface_result = #{record.interfaceResult,jdbcType=VARCHAR},
      </if>
      <if test="record.retryCount != null" >
        retry_count = #{record.retryCount,jdbcType=INTEGER},
      </if>
      <if test="record.status != null" >
        status = #{record.status,jdbcType=INTEGER},
      </if>
      <if test="record.requestTime != null" >
        request_time = #{record.requestTime,jdbcType=TIMESTAMP},
      </if>
      <if test="record.responseTime != null" >
        response_time = #{record.responseTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    <!--
      WARNING - @mbg.generated
    -->
    update spv_schedule_log
    set uuid = #{record.uuid,jdbcType=CHAR},
      created_on = #{record.createdOn,jdbcType=TIMESTAMP},
      created_by = #{record.createdBy,jdbcType=CHAR},
      updated_on = #{record.updatedOn,jdbcType=TIMESTAMP},
      updated_by = #{record.updatedBy,jdbcType=CHAR},
      version = #{record.version,jdbcType=INTEGER},
      group_code = #{record.groupCode,jdbcType=VARCHAR},
      batch_no = #{record.batchNo,jdbcType=VARCHAR},
      batch_result = #{record.batchResult,jdbcType=VARCHAR},
      main_uuid = #{record.mainUuid,jdbcType=CHAR},
      main_table = #{record.mainTable,jdbcType=VARCHAR},
      schedule_name = #{record.scheduleName,jdbcType=VARCHAR},
      schedule_description = #{record.scheduleDescription,jdbcType=VARCHAR},
      schedule_sql = #{record.scheduleSql,jdbcType=VARCHAR},
      params_str = #{record.paramsStr,jdbcType=OTHER},
      interface_url = #{record.interfaceUrl,jdbcType=VARCHAR},
      interface_result = #{record.interfaceResult,jdbcType=VARCHAR},
      retry_count = #{record.retryCount,jdbcType=INTEGER},
      status = #{record.status,jdbcType=INTEGER},
      request_time = #{record.requestTime,jdbcType=TIMESTAMP},
      response_time = #{record.responseTime,jdbcType=TIMESTAMP}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
</mapper>

可以看到也是自动生成了

下面我们开始配置怎么使用:

配置application.yml

#Mysql配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/ccclubs_t3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC #配置数据库的路径
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource  #这个可以看一下 https://blog.csdn.net/qq_27191423/article/details/79146855
    druid:
      driver-class-name: com.mysql.jdbc.Driver
      filters: stat
      maxActive: 20   #连接池的最大值,同一时间可以从池分配的最多连接数量,0时无限制
      initialSize: 1   #连接初始值,连接池启动时创建的连接数量的初始值
      maxWait: 60000
      minIdle: 1   #最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true    #是否对已备语句进行池管理(布尔值),是否对PreparedStatement进行缓存
      maxOpenPreparedStatements: 20
#mybatis 配置
mybatis:
  mapper-locations: classpath*:mapper/*.xml  #指定xml所在的路径
  type-aliases-package: com.hf.commonmapper.model  #指定实体类所在包路径
  configuration:
    map-underscore-to-camel-case: true  #驼峰开启
#通用mapper配置
mapper:
  mappers: com.hf.commonmapper.common.BaseMapper #需要指定通用mapper所在的类
  not-empty: false
  identity: MYSQL
#mybatis打印sql日志
logging:
  level:
    com.hf.commonmapper.mapper: debug   #key为mapper文件所在的包路径,好像只有debug有效额
#pagehelper分页插件
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params:
    count: countSql

需要在启动类中扫描mapper接口包路径,注意这个扫描一定不能扫描到通用mapper所在的路径,并且@MapperScan注解必须是tk.mybatis下面的注解,而不能是mybatis的注解

启动类如下:

package com.hf.commonmapper;

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

@SpringBootApplication
@MapperScan("com.hf.commonmapper.mapper")   //特别需要注意@MapperScan这个注解必须是tk.mybatis这个包下面的,而不是mybatis下面的,别导错了
public class CommonMapperApplication {

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

}

以上的配置都完成了,下面测试:

package com.hf.commonmapper.service;

import com.hf.commonmapper.model.SpvScheduleLog;
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 service.SpvScheduleLogService;

import java.util.List;

/**
 * @Description:
 * @Date: 2019/5/7
 * @Auther: wm yu
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpvScheduleLogServiceTest {

    @Autowired
    private SpvScheduleLogService spvScheduleLogService;

    @Test
    public void queryAll(){
        List<SpvScheduleLog> logs = spvScheduleLogService.queryAll();
        System.out.println(logs);
    }

}

service接口:

package com.hf.commonmapper.service;

import com.hf.commonmapper.model.SpvScheduleLog;

import java.util.List;

/**
 * @Description:
 * @Date: 2019/5/7
 * @Auther:
 */
public interface SpvScheduleLogService {

    List<SpvScheduleLog> queryAll();

}

实现类接口:

package com.hf.commonmapper.service.impl;

import com.hf.commonmapper.mapper.SpvScheduleLogMapper;
import com.hf.commonmapper.model.SpvScheduleLog;
import com.hf.commonmapper.model.SpvScheduleLogExample;
import com.hf.commonmapper.service.SpvScheduleLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Date: 2019/5/7
 * @Auther: 
 */
@Slf4j
@Service
public class SpvScheduleLogServiceImpl implements SpvScheduleLogService {

    @Autowired
    private SpvScheduleLogMapper spvScheduleLogMapper;

    @Override
    public List<SpvScheduleLog> queryAll() {
        SpvScheduleLogExample example = new SpvScheduleLogExample();
        List<SpvScheduleLog> logs = spvScheduleLogMapper.selectByExample(example);
        return logs;
    }
}

debug输出结果如下:

可以看到在debug状态下,sql已经显示出来了,并且结果也查询出来了

以上就是在spring boot中结合mybatis的generator和通用mapper的使用

其实上面的可以修改一下,使其更简单,方法如下:

首先,将通用mapper的接口类,也就是我们定义的BaseMapper去继承2个tk中的接口,如下

package com.hf.commonmapper.common;

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

/**
 * @Description:
 * @Date: 2019/5/7
 * @Auther: 
 */
public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

这个时候,如果你直接去启动项目的话,会报错,大概是说在mapper接口和对应的xml文件中已经存在下面的这些方法了

为什么呢?  

原因很简单,在你继承的接口Mapper<T>, MySqlMapper<T>中已经存在封装好了这些方法了,而mybatis的mapper接口中是使用方法名作为statementId,也就是必须唯一标识,所以你需要去掉所有自动生成的方法和对应的xml 配置,此时你在启动的时候就一样了

如下:

package com.hf.commonmapper.mapper;

import com.hf.commonmapper.common.BaseMapper;
import com.hf.commonmapper.model.SpvScheduleLog;

public interface SpvScheduleLogMapper extends BaseMapper<SpvScheduleLog> {
    /*int countByExample(SpvScheduleLogExample example);

    int deleteByExample(SpvScheduleLogExample example);

    List<SpvScheduleLog> selectByExample(SpvScheduleLogExample example);

    int updateByExampleSelective(@Param("record") SpvScheduleLog record, @Param("example") SpvScheduleLogExample example);

    int updateByExample(@Param("record") SpvScheduleLog record, @Param("example") SpvScheduleLogExample example);*/
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hf.commonmapper.mapper.SpvScheduleLogMapper" >
  <resultMap id="BaseResultMap" type="com.hf.commonmapper.model.SpvScheduleLog" >
    <!--
      WARNING - @mbg.generated
    -->
    <id column="uuid" property="uuid" jdbcType="CHAR" />
    <result column="created_on" property="createdOn" jdbcType="TIMESTAMP" />
    <result column="created_by" property="createdBy" jdbcType="CHAR" />
    <result column="updated_on" property="updatedOn" jdbcType="TIMESTAMP" />
    <result column="updated_by" property="updatedBy" jdbcType="CHAR" />
    <result column="version" property="version" jdbcType="INTEGER" />
    <result column="group_code" property="groupCode" jdbcType="VARCHAR" />
    <result column="batch_no" property="batchNo" jdbcType="VARCHAR" />
    <result column="batch_result" property="batchResult" jdbcType="VARCHAR" />
    <result column="main_uuid" property="mainUuid" jdbcType="CHAR" />
    <result column="main_table" property="mainTable" jdbcType="VARCHAR" />
    <result column="schedule_name" property="scheduleName" jdbcType="VARCHAR" />
    <result column="schedule_description" property="scheduleDescription" jdbcType="VARCHAR" />
    <result column="schedule_sql" property="scheduleSql" jdbcType="VARCHAR" />
    <result column="params_str" property="paramsStr" jdbcType="OTHER" />
    <result column="interface_url" property="interfaceUrl" jdbcType="VARCHAR" />
    <result column="interface_result" property="interfaceResult" jdbcType="VARCHAR" />
    <result column="retry_count" property="retryCount" jdbcType="INTEGER" />
    <result column="status" property="status" jdbcType="INTEGER" />
    <result column="request_time" property="requestTime" jdbcType="TIMESTAMP" />
    <result column="response_time" property="responseTime" jdbcType="TIMESTAMP" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <!--
      WARNING - @mbg.generated
    -->
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <!--
      WARNING - @mbg.generated
    -->
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    <!--
      WARNING - @mbg.generated
    -->
    uuid, created_on, created_by, updated_on, updated_by, version, group_code, batch_no, 
    batch_result, main_uuid, main_table, schedule_name, schedule_description, schedule_sql, 
    params_str, interface_url, interface_result, retry_count, status, request_time, response_time
  </sql>





  <!--<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.hf.commonmapper.model.SpvScheduleLogExample" >
    &lt;!&ndash;
      WARNING - @mbg.generated
    &ndash;&gt;
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from spv_schedule_log
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <delete id="deleteByExample" parameterType="com.hf.commonmapper.model.SpvScheduleLogExample" >
    &lt;!&ndash;
      WARNING - @mbg.generated
    &ndash;&gt;
    delete from spv_schedule_log
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <select id="countByExample" parameterType="com.hf.commonmapper.model.SpvScheduleLogExample" resultType="java.lang.Integer" >
    &lt;!&ndash;
      WARNING - @mbg.generated
    &ndash;&gt;
    select count(*) from spv_schedule_log
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    &lt;!&ndash;
      WARNING - @mbg.generated
    &ndash;&gt;
    update spv_schedule_log
    <set >
      <if test="record.uuid != null" >
        uuid = #{record.uuid,jdbcType=CHAR},
      </if>
      <if test="record.createdOn != null" >
        created_on = #{record.createdOn,jdbcType=TIMESTAMP},
      </if>
      <if test="record.createdBy != null" >
        created_by = #{record.createdBy,jdbcType=CHAR},
      </if>
      <if test="record.updatedOn != null" >
        updated_on = #{record.updatedOn,jdbcType=TIMESTAMP},
      </if>
      <if test="record.updatedBy != null" >
        updated_by = #{record.updatedBy,jdbcType=CHAR},
      </if>
      <if test="record.version != null" >
        version = #{record.version,jdbcType=INTEGER},
      </if>
      <if test="record.groupCode != null" >
        group_code = #{record.groupCode,jdbcType=VARCHAR},
      </if>
      <if test="record.batchNo != null" >
        batch_no = #{record.batchNo,jdbcType=VARCHAR},
      </if>
      <if test="record.batchResult != null" >
        batch_result = #{record.batchResult,jdbcType=VARCHAR},
      </if>
      <if test="record.mainUuid != null" >
        main_uuid = #{record.mainUuid,jdbcType=CHAR},
      </if>
      <if test="record.mainTable != null" >
        main_table = #{record.mainTable,jdbcType=VARCHAR},
      </if>
      <if test="record.scheduleName != null" >
        schedule_name = #{record.scheduleName,jdbcType=VARCHAR},
      </if>
      <if test="record.scheduleDescription != null" >
        schedule_description = #{record.scheduleDescription,jdbcType=VARCHAR},
      </if>
      <if test="record.scheduleSql != null" >
        schedule_sql = #{record.scheduleSql,jdbcType=VARCHAR},
      </if>
      <if test="record.paramsStr != null" >
        params_str = #{record.paramsStr,jdbcType=OTHER},
      </if>
      <if test="record.interfaceUrl != null" >
        interface_url = #{record.interfaceUrl,jdbcType=VARCHAR},
      </if>
      <if test="record.interfaceResult != null" >
        interface_result = #{record.interfaceResult,jdbcType=VARCHAR},
      </if>
      <if test="record.retryCount != null" >
        retry_count = #{record.retryCount,jdbcType=INTEGER},
      </if>
      <if test="record.status != null" >
        status = #{record.status,jdbcType=INTEGER},
      </if>
      <if test="record.requestTime != null" >
        request_time = #{record.requestTime,jdbcType=TIMESTAMP},
      </if>
      <if test="record.responseTime != null" >
        response_time = #{record.responseTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    &lt;!&ndash;
      WARNING - @mbg.generated
    &ndash;&gt;
    update spv_schedule_log
    set uuid = #{record.uuid,jdbcType=CHAR},
      created_on = #{record.createdOn,jdbcType=TIMESTAMP},
      created_by = #{record.createdBy,jdbcType=CHAR},
      updated_on = #{record.updatedOn,jdbcType=TIMESTAMP},
      updated_by = #{record.updatedBy,jdbcType=CHAR},
      version = #{record.version,jdbcType=INTEGER},
      group_code = #{record.groupCode,jdbcType=VARCHAR},
      batch_no = #{record.batchNo,jdbcType=VARCHAR},
      batch_result = #{record.batchResult,jdbcType=VARCHAR},
      main_uuid = #{record.mainUuid,jdbcType=CHAR},
      main_table = #{record.mainTable,jdbcType=VARCHAR},
      schedule_name = #{record.scheduleName,jdbcType=VARCHAR},
      schedule_description = #{record.scheduleDescription,jdbcType=VARCHAR},
      schedule_sql = #{record.scheduleSql,jdbcType=VARCHAR},
      params_str = #{record.paramsStr,jdbcType=OTHER},
      interface_url = #{record.interfaceUrl,jdbcType=VARCHAR},
      interface_result = #{record.interfaceResult,jdbcType=VARCHAR},
      retry_count = #{record.retryCount,jdbcType=INTEGER},
      status = #{record.status,jdbcType=INTEGER},
      request_time = #{record.requestTime,jdbcType=TIMESTAMP},
      response_time = #{record.responseTime,jdbcType=TIMESTAMP}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>-->
</mapper>

如上面将其全部注释掉,在测试发现效果是一样的...

好了,这篇博客就先到这里了,完成!

猜你喜欢

转载自blog.csdn.net/qq_42151769/article/details/89914737