6.1 Spring Boot集成mybatis

6.1 Spring Boot集成mybatis

在SpringBoot集成MyBatis时,我们将去掉和Mybatis配置相关的xml文件配置方式,用注解和属性配置来代替这些繁杂的配置。

本节我们使用SpringBoot集成Mybatis开发一个简易的H5性能测试的Web后台。我们采用Java,Groovy混合编程的方式。

新建gradle工程

组织工程目录结构如下

.
├── build.gradle
├── settings.gradle
└── src
    ├── main
    │   ├── groovy
    │   ├── java
    │   └── resources
    │       └── application.yml
    └── test
        ├── groovy
        ├── java
        └── resources

9 directories, 3 files

配置build.gradle

添加mybatis-spring-boot-starter依赖

compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.1.1')

该starter将会自动配置好Spring Boot集成mybatis需要的mybatis,mybatis-spring等所有依赖。这个starter的依赖树如下图所示:

其中,mybatis-spring-boot-autoconfigure会完成我们之前使用xml配置mybatis使用的sqlmap-config.xml类似如下配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="lazyLoadingEnabled" value="false"></setting>
    </settings>
</configuration>

和data-source.xml文件配置数据源dataSource和TransactionManager,

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

        <!-- 数据源定义 -->
       <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://127.0.0.1:3306/h5perf?useUnicode=true&autoReconnect=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>root</value>
        </property>
    </bean>


    <!-- TransactionManager定义。 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="transactionTemplate"
          class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>


    <!-- 通过aop定义事务增强切面 -->
    <aop:config>
        <aop:pointcut id="serviceMethod" expression="execution(* com.easy.springboot.h5perf.service.*.*(..))"/>
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="false"/>
            <tx:method name="save*" rollback-for="Exception"/>
            <tx:method name="new*" rollback-for="Exception"/>
            <tx:method name="update*" rollback-for="Exception"/>
            <tx:method name="*" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>

    <!-- MyBatis配置sqlSessionFactory, SQL Map -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描entity目录 -->
        <property name="typeAliasesPackage" value="com.easy.springboot.h5perf.model"/>
        <!-- 显式指定Mapper文件位置 -->
        <property name="mapperLocations"
                  value="classpath:/sqlmap/*Mapper.xml"/>
        <property name="configLocation" value="classpath:sqlmap-config.xml"></property>
    </bean>
    <!-- 扫描basePackage下所有以@MyBatisRepository标识的 接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:basePackage="com.alibaba.swork.info.common.mapper"/>

</beans>

配置application.yml

配置数据源

spring:
    datasource:
        name: h5perf
        url: jdbc:mysql://localhost:3306/h5perf?autoReconnect=true&useSSL=false
        username: root
        password: root
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver

配置mybatis

mybatis:
    type-aliases-package: com.easy.springboot.h5perf.model
    configuration:
        # 开启mybatis开启数据库字段自动映射驼峰命名规则java属性
        map-underscore-to-camel-case: true
        default-fetch-size: 100
        default-statement-timeout: 30

数据库表结构

CREATE DATABASE IF NOT EXISTS `h5perf`
  DEFAULT CHARACTER SET utf8;
USE `h5perf`;

DROP TABLE IF EXISTS `test_case`;

CREATE TABLE `test_case` (
  `id`             INT(11) NOT NULL AUTO_INCREMENT,
  `container_type` VARCHAR(45)      DEFAULT NULL
  COMMENT '‘ORIGIN_WEBVIEW’,’UC_WEBVIEW’',
  `test_url`       VARCHAR(45)      DEFAULT NULL,
  `net_type`       VARCHAR(45)      DEFAULT NULL
  COMMENT '‘WIFI’,‘3G’,‘4G’',
  `gmt_created`    DATETIME         DEFAULT NULL,
  `gmt_modified`   DATETIME         DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;


DROP TABLE IF EXISTS `test_resource`;

CREATE TABLE `test_resource` (
  `id`            INT(11) NOT NULL AUTO_INCREMENT,
  `test_case_id`  INT(11)          DEFAULT NULL,
  `start_time`    BIGINT(11)       DEFAULT NULL,
  `resource_url`  VARCHAR(500)     DEFAULT NULL,
  `resource_type` VARCHAR(45)      DEFAULT NULL
  COMMENT 'IMG,JS,CSS,OTHER',
  `resource_time` BIGINT(11)       DEFAULT NULL
  COMMENT 'onLoadResource资源时间戳',
  `resource_size` BIGINT(11)       DEFAULT NULL
  COMMENT '资源大小',
  `gmt_created`   DATETIME         DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;


DROP TABLE IF EXISTS `test_time_data`;

CREATE TABLE `test_time_data` (
  `id`               INT(11) NOT NULL AUTO_INCREMENT,
  `test_case_id`     INT(11)          DEFAULT NULL,
  `on_recieve_title` VARCHAR(45)      DEFAULT NULL
  COMMENT '近似白屏时间',
  `on_page_finished` VARCHAR(45)      DEFAULT NULL
  COMMENT '页面加载完成时间',
  `dom_content_load` VARCHAR(45)      DEFAULT NULL
  COMMENT 'dom内容加载完成时间',
  `load`             VARCHAR(45)      DEFAULT NULL
  COMMENT '资源加载完成时间',
  `gmt_created`      DATETIME         DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

Model层代码

我们在application.yml中开启了mybatis开启数据库字段自动映射驼峰命名规则java属性:

map-underscore-to-camel-case: true

所以,我们model类的属性命名规则按照驼峰命名规则。

TestCase.groovy代码:

package com.easy.springboot.h5perf.model

/**
 * Created by jack on 2017/4/22.
 */
class TestCase {
    Integer id
    String containerType
    String testUrl
    String netType
    Date gmtCreated
    Date gmtModified

    @Override
    String toString() {
        return "TestCase{" +
                "id=" + id +
                ", containerType='" + containerType + '\'' +
                ", testUrl='" + testUrl + '\'' +
                ", netType='" + netType + '\'' +
                ", gmtCreated=" + gmtCreated +
                ", gmtModified=" + gmtModified +
                '}';
    }
}


Mapper接口层代码

我们以往的通过xml配置显式指定Mapper文件位置:

<!-- 显式指定Mapper文件位置 -->
        <property name="mapperLocations"
                  value="classpath:/sqlmap/*Mapper.xml"/>

我们现在用注解方式,直接在接口上添加@Mapper注解即可。代码示例TestCaseMapper.groovy

package com.easy.springboot.h5perf.mapper

import com.easy.springboot.h5perf.model.TestCase
import org.apache.ibatis.annotations.Insert
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Options
import org.apache.ibatis.annotations.Param
import org.apache.ibatis.annotations.Select

@Mapper
interface TestCaseMapper {

    @Insert([
            "insert into test_case",
            "set container_type = #{t.containerType},",
            "test_url = #{t.testUrl},",
            "net_type = #{t.netType},",
            "gmt_created = #{t.gmtCreated},",
            "gmt_modified = #{t.gmtModified}"
    ])
    @Options(useGeneratedKeys = true, keyProperty = "t.id")
    int insert(@Param("t") TestCase testCase)

    @Select("select * from test_case")
    List<TestCase> findAll()

    @Select("select * from test_case where net_type=#{netType}")
    List<TestCase> findByNetType(@Param(value="netType")String netType)

    @Select("select * from test_case where id=#{id} limit 1")
    TestCase findOne(@Param(value="id")Integer id)

    int insertSelective(TestCase record)
}

Controller层代码

package com.easy.springboot.h5perf.controller

import com.easy.springboot.h5perf.model.TestCase
import com.easy.springboot.h5perf.result.Result
import com.easy.springboot.h5perf.service.TestCaseService
import com.github.pagehelper.PageInfo
import groovy.json.JsonOutput
import io.swagger.annotations.Api
import io.swagger.annotations.ApiImplicitParam
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

/**
 * Created by jack on 2017/4/22.
 * http://springfox.github.io/springfox/docs/current/#springfox-samples
 */

//在Controller上使用@Api会生成这个Controller的整体描述
@Api(value = "测试任务管理", tags = ["测试任务管理API"], description = "描述信息")
@Controller
class TestCaseController {
    @Autowired
    TestCaseService testCaseService

    @PostMapping("/saveTestCase")
    @ResponseBody
    def saveTestCase(TestCase testCase) {
        testCase.gmtCreated = new Date()
        println("testCase===" + testCase)
        int insert = testCaseService.save(testCase)
        println("testCase===" + testCase)
        Result result = new Result()
        if (insert == 1) {
            result.success = true
            result.result = testCase
        } else {
            result.success = false
            result.result = testCase
        }
        def jsonOutput = new JsonOutput()
        println("saveTestCase result===" + jsonOutput.toJson(result))
        result
    }

    @GetMapping("/listTestCase")
    def listTestCase(Model model,
                     @RequestParam(value = "pageNo", required = false) Integer pageNo,
                     @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        def pageInfo = testCaseService.findAll(pageNo, pageSize)
        model.addAttribute("testCaseList", pageInfo.list)
        model.addAttribute("pageNo", pageInfo.pageNum)
        model.addAttribute("totalPage", pageInfo.pages)
        model.addAttribute("prePage", pageInfo.prePage)
        model.addAttribute("nextPage", pageInfo.nextPage)
        model.addAttribute("hasPreviousPage", pageInfo.hasPreviousPage)
        model.addAttribute("hasNextPage", pageInfo.hasNextPage)

        "/test_case/list"
    }

//    在具体方法上使用@ApiOperation可以生成接口的描述
    @ApiOperation(value = "list all TestCase Json", notes = "listTestCaseJson", produces = "application/json")
    @GetMapping("/listTestCaseJson")
    @ResponseBody
    def listTestCaseJson(@RequestParam(value = "pageNo", required = false) Integer pageNo,
                         @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        testCaseService.findAll(pageNo, pageSize)
    }

    @ApiOperation(value = "findOne TestCase Json", notes = "findOne TestCase", produces = "application/json")
//  在方法上使用@ApiImplicitParam可以增加对参数等的描述
    @ApiImplicitParam(name = "id",
            value = "测试任务ID",
            dataType = "Integer",//This can be the class name or a primitive
            required = true,
            paramType = "query")
//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}
    @GetMapping("/findOne")
    @ResponseBody
    def findOne(@RequestParam(value = "id", required = true) Integer id) {
        testCaseService.findOne(id)
    }

    @ApiOperation(value = "findByNetType TestCase Json", notes = "findByNetType TestCase", produces = "application/json")
//  在方法上使用@ApiImplicitParam可以增加对参数等的描述
    @ApiImplicitParam(name = "netType",
            value = "findByNetType",
            dataType = "String",//This can be the class name or a primitive
            required = true,
            paramType = "query")
    @GetMapping("/findByNetType")
    @ResponseBody
    def findByNetType(@RequestParam(value = "netType", required = false) String netType,
                      @RequestParam(value = "pageNo", required = false) Integer pageNo,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize
    ) {
        testCaseService.queryByPage(netType, pageNo, pageSize)
    }


}

使用PageHelper实现后端分页

(1)添加pagehelper-spring-boot-starter

//   pagehelper
    compile('com.github.pagehelper:pagehelper-spring-boot-starter:1.1.0')

(2)Service层代码实现

接口类 TestCaseService.groovy

package com.easy.springboot.h5perf.service

import com.easy.springboot.h5perf.model.TestCase
import com.github.pagehelper.PageInfo

/**
 * Created by jack on 2017/4/23.
 */
interface TestCaseService {
    def save(TestCase testCase)

    PageInfo<TestCase> findAll(Integer pageNo, Integer pageSize)

    TestCase findOne(Integer id)

    PageInfo<TestCase> queryByPage(String netType, Integer pageNo, Integer pageSize)

}



实现类TestCaseServiceImpl.groovy

package com.easy.springboot.h5perf.service

import com.easy.springboot.h5perf.mapper.TestCaseMapper
import com.easy.springboot.h5perf.model.TestCase
import com.github.pagehelper.PageHelper
import com.github.pagehelper.PageInfo
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * Created by jack on 2017/4/23.
 */
@Service
class TestCaseServiceImpl implements TestCaseService {
    @Autowired
    TestCaseMapper testCaseMapper;

    @Override
    def save(TestCase testCase) {
        testCaseMapper.insert(testCase)
    }

    @Override
    PageInfo<TestCase> findAll(Integer pageNo, Integer pageSize) {
        pageNo = pageNo == null ? 1 : pageNo
        pageSize = pageSize == null ? 10 : pageSize
        PageHelper.startPage(pageNo, pageSize)
        List<TestCase> testCaseList = testCaseMapper.findAll()
        //用PageInfo对结果进行包装
        PageInfo<TestCase> testCasePageInfo = new PageInfo<>(testCaseList)
        testCasePageInfo

    }

    @Override
    TestCase findOne(Integer id) {
        testCaseMapper.findOne(id)
    }

    @Override
    PageInfo<TestCase> queryByPage(String netType, Integer pageNo, Integer pageSize) {
        pageNo = pageNo == null ? 1 : pageNo
        pageSize = pageSize == null ? 10 : pageSize
        PageHelper.startPage(pageNo, pageSize)

        List<TestCase> testCaseList = testCaseMapper.findByNetType(netType)
        //用PageInfo对结果进行包装
        PageInfo<TestCase> testCasePageInfo = new PageInfo<>(testCaseList)
        testCasePageInfo
    }
}

(3)Controller层与前端代码集成

传到前端的Model层数据:

    @GetMapping("/listTestCase")
    def listTestCase(Model model,
                     @RequestParam(value = "pageNo", required = false) Integer pageNo,
                     @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        def pageInfo = testCaseService.findAll(pageNo, pageSize)
        model.addAttribute("testCaseList", pageInfo.list)
        model.addAttribute("pageNo", pageInfo.pageNum)
        model.addAttribute("totalPage", pageInfo.pages)
        model.addAttribute("prePage", pageInfo.prePage)
        model.addAttribute("nextPage", pageInfo.nextPage)
        model.addAttribute("hasPreviousPage", pageInfo.hasPreviousPage)
        model.addAttribute("hasNextPage", pageInfo.hasNextPage)

        "/test_case/list"
    }

前端使用Bootstrap pagination样式类:

    <table class="table table-hover">
        <thead>
        <th>Id</th>
        <th>testUrl</th>
        <th>containerType</th>
        <th>netType</th>
        <th>gmtCreated</th>
        </thead>
        <tbody>
        <#list testCaseList as tc >
        <tr>
            <td>${tc.id}</td>
            <td><a href="${tc.testUrl}">${tc.testUrl}</a></td>
            <td>${tc.containerType}</td>
            <td>${tc.netType}</td>
            <td>${tc.gmtCreated?string('yyyy/MM/dd HH:mm:ss')}</td>
        </tr>
        </#list>
        </tbody>
    </table>


    <div class="center">
        <ul class="pagination">
            <li><a href="/listTestCase?pageNo=${prePage}&pageSize=10">«</a></li>
        <#list 1..totalPage as index>
            <#if index=pageNo>
                <li class="active"><a href="/listTestCase?pageNo=${index}&pageSize=10">${index}</a></li>
            <#else>
                <li><a href="/listTestCase?pageNo=${index}&pageSize=10">${index}</a></li>
            </#if>
        </#list>
            <li><a href="/listTestCase?pageNo=${nextPage}&pageSize=10">»</a></li>
        </ul>
    </div>

(4)运行测试

第1页
第2页

另外,我们还可以集成Druid对数据库进行监控。相关的资料可以去网上搜索学习。本章节不再赘述。

本节完整的工程源代码:https://github.com/EasySpringBoot/h5perf

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容