SpringBoot集成Mybatis

本文详细介绍如何在SpringBoot环境中集成Mybatis,包括环境搭建、依赖配置、逆向工程生成代码、服务层实现及测试、控制器返回视图等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0.搭建环境

   0.1 IDE:IntelliJ IDEA 2017.3.2 x64

   0.2 database:MySQL 5.7.20

   0.3 JDK:1.8.131

1.Create New Project-->Spring Initlizr

2. 选中相关配置

    2.1 Web-->Web

    2.2 SQL-->MySQL&JDBC&Mybatis

    2.3 Template Engines-->Freemarker

点击Next-->Finish即可构建成功!

3.将application.properties修改为application.yml文件

  3.1 选中该文件右键找到Refator

  3.2 将后缀该为yml文件即可

4. 添加相关pom依赖

   4.1 pagehelper分页插件

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

   4.2 alibaba的druid数据库连接池

 <!-- SpringBoot使用alibaba的druid数据库连接池 -->
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>1.1.10</version>
</dependency>

   4.3 jackson

<!--jackson  -->
<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-core</artifactId>
</dependency>

<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
     <groupId>com.fasterxml.jackson.datatype</groupId>
     <artifactId>jackson-datatype-joda</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>

  4.4 完整pom

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <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>1.3.2</version>
        </dependency>

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

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

        <!-- SpringBoot使用alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!--jackson  -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>

  4.5 在pom文件bulid标签中添加相关配置

       4.5.1  添加resources配置

        <resources>
            <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <!--解决resouces文件放入target文件夹的问题-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>*.properties</include>
                    <include>*.xml</include>
                    <include>*.yml</include>
                    <!--添加模板支持-->
                    <include>templates/*.ftl</include>
                    <!--<include>*.ftl</include>-->
                </includes>
            </resource>
        </resources>

       4.6.1 mybatis-generator 自动生成代码插件 添加到bulid-->plugins中

           <!-- mybatis generator 自动生成代码插件  -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <dependencies>
                    <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.44</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>

5.添加相关配置到application.yml

  5.1 修改启动端口号

#配置启动端口号 只要端口不冲突 可以随便取
server:
  port: 2001

  5.2 指定项目名

  #  设置启动项目名 与项目名一致即可 也可以随便取
  servlet:
    context-path: /gowinxin

  5.3 配置数据源

#配置数据源
spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        #请修改为自己的数据库并且修改username&password
        url: jdbc:mysql://192.168.43.82:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
        username: root
        password: 123
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

  5.4 开放静态资源

#请放在spring节点下    
#    开放静态资源
    resources:
      static-locations: /static/**

  5.5 配置freemarker相关配置

#     配置freemarkerx相关配置
    freemarker:
        request-context-attribute: req  #req访问request
        suffix: .ftl  #后缀名
        content-type: text/html
        enabled: true
        cache: false #缓存配置
        template-loader-path: classpath:/templates/ #模板加载路径 按需配置
        charset: UTF-8 #编码格式
        settings:
          number_format: '0.##' #数字格式化,无小数点

  5.6 配置Mybatis相关信息

mybatis:
  mapper-locations: classpath*:mapper/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.go.gowinxin.model
  configuration:
#  开启驼峰命名
    map-underscore-to-camel-case: true
#   设置打印日志为sql、参数、查询结果的
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

  5.7 添加pagehelper分页插件相关信息

#pagehelper分页插件
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

5.8 完整配置

#配置启动端口号 只要端口不冲突 可以随便取
server:
  port: 2001
    #  设置启动项目名 与项目名一致即可 也可以随便取
  servlet:
      context-path: /dwinxin

#配置数据源
spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        #请修改为自己的数据库并且修改username&password
        url: jdbc:mysql://192.168.43.82:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
        username: root
        password: 123
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
    #请放在spring节点下
    #    开放静态资源
    resources:
          static-locations: /static/**
    #     配置freemarkerx相关配置
    freemarker:
            request-context-attribute: req  #req访问request
            suffix: .ftl  #后缀名
            content-type: text/html
            enabled: true
            cache: false #缓存配置
            template-loader-path: classpath:/templates/ #模板加载路径 按需配置
            charset: UTF-8 #编码格式
            settings:
              number_format: '0.##' #数字格式化,无小数点

mybatis:
  mapper-locations: classpath*:mapper/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.go.gowinxin.model
  configuration:
#  开启驼峰命名
    map-underscore-to-camel-case: true
#   设置打印日志为sql、参数、查询结果的
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl


#pagehelper分页插件
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

6.创建相关的包

  • utils
  • model
  • mapper
  • service
  • controller

注:该包都要创建在后缀Application.java文件下

7.在后缀Application.java文件下加上的@MapperScan注解 指定对应的包名

这时候就可以启动测试啦,如果没报错表示配置成功啦!

8.开发

  8.1 通过Mybatis逆向工程生成mapper&model

        8.1.1 创建generatorConfig.xml 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>

    <!-- 导入配置属性 -->
    <properties resource="jdbc.properties"></properties>
    <!-- !!!! Driver Class Path !!!! -->
    <classPathEntry location="${jdbc.driverLocation}"/>

    <context id="context" targetRuntime="MyBatis3">
        <commentGenerator>
            <!--去除多余注释-->
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <!-- !!!! Database Configurations !!!! -->
        <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}"
                        password="${jdbc.}"/>

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

        <!-- !!!! Model Configurations !!!! -->
        <javaModelGenerator targetPackage="com.go.gowinxin.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- !!!! Mapper XML Configurations !!!! -->
        <sqlMapGenerator targetPackage="com.go.gowinxin.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- !!!! Mapper Interface Configurations !!!! -->
        <javaClientGenerator targetPackage="com.go.gowinxin.mapper" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- !!!! Table Configurations !!!! -->
        <!--<table tableName="t_user" domainObjectName="User"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_config_file_first_kind" domainObjectName="ConfigFileFirstKind"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_config_file_second_kind" domainObjectName="ConfigFileSecondKind"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_config_file_third_kind" domainObjectName="ConfigFileThirdKind"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_config_question_first_kind" domainObjectName="ConfigQuestionFirstKind"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_config_question_second_kind" domainObjectName="ConfigQuestionSecondKind"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_config_public_char" domainObjectName="ConfigPublicChar"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_config_primary_key" domainObjectName="ConfigPrimaryKey"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_config_major_kind" domainObjectName="ConfigMajorKind"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_config_major" domainObjectName="ConfigMajor"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_human_file_dig" domainObjectName="HumanFileDig"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_human_file" domainObjectName="HumanFile"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_salary_standard_details" domainObjectName="SalaryStandardDetails"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_salary_standard" domainObjectName="SalaryStandard"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_bonus" domainObjectName="Bonus"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_training" domainObjectName="Training"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_major_change" domainObjectName="MajorChange"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_salary_grant" domainObjectName="SalaryGrant"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_salary_grant_details" domainObjectName="SalaryGrantDetails"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_engage_major_release" domainObjectName="EngageMajorRelease"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_engage_exam_details" domainObjectName="EngageExamDetails"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_engage_exam" domainObjectName="EngageExam"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_engage_answer" domainObjectName="EngageAnswer"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_engage_answer_details" domainObjectName="EngageAnswerDetails"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_engage_subjects" domainObjectName="EngageSubjects"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_engage_resume" domainObjectName="EngageResume"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_engage_interview" domainObjectName="EngageInterview"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->


        <!--<table tableName="t_tree_node" domainObjectName="TreeNode"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_sys_user" domainObjectName="SysUser"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_sys_role" domainObjectName="SysRole"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_sys_permission" domainObjectName="SysPermission"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <!--<table tableName="t_sys_user_role" domainObjectName="SysUserRole"-->
        <!--enableCountByExample="false"-->
        <!--enableDeleteByExample="false"-->
        <!--enableSelectByExample="false"-->
        <!--enableUpdateByExample="false"/>-->

        <table tableName="t_book" domainObjectName="Book"
               enableCountByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               enableUpdateByExample="false"/>


    </context>
</generatorConfiguration>

        8.1.2 创建maven执行项 命令:mybatis-generator:generate -e

  执行逆向生成即可!

  8.2 书写service层

  • IBookService
    • BookServiceImpl

  8.3 测试service层

        8.3.1 书写BaseTestCase

package com.go.gowinxin.base.test;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Create on 2018/9/22 on Dong
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BaseTestCase {


    @Before
    public void before() {
        
    }

}

        8.3.2 测试service类继承与BaseTestCase类

package com.go.dwinxin.service;

import com.go.dwinxin.BaseTestCase;
import com.go.dwinxin.model.Book;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Create on 2018/11/6 on Dong
 */
public class IBookServiceTest extends BaseTestCase {

    @Autowired
    private IBookService bookService;

    private Book book;

    @Override
    public void before() {
        super.before();
        book = new Book();
    }

    @Test
    public void testListBook() {
        final List<Book> bookList = bookService.listBook(book);
        for (Book b : bookList) {
            System.out.println(b);
        }
    }

}

9.controller返回视图freemarker

   9.1 书写Controller 

package com.go.dwinxin.controller;

import com.go.dwinxin.model.Book;
import com.go.dwinxin.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * Create on 2018/11/6 on Dong
 */
@Controller
public class BookController {

    @Autowired
    private IBookService bookService;

    @RequestMapping(value = {"/"})
    public String toIndex(Model model, Book book) {
        final List<Book> bookList = bookService.listBook(book);
        model.addAttribute("bookList", bookList);
        return "index";
    }
}

   9.2 返回freemarker视图 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot集成Mybatis</title>
</head>
<body>

<#--使用freemarker表达式 显示数据-->
<#list bookList as book>
    ${book}<br>
</#list>

</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值