Springboot系列之Springboot与Mybatis整合

前言

技术博客那么多,为什么自己整理呢?太过零散的知识点不易记忆,且查找的时候也不是太方便,眼过千遍不如手过一遍的操作一遍,即使Springboot已经很好的整合了各项的技术框架,但实际操作的时候也会发现一些问题。我会将可能出现的问题记录一下,博文时刻更新。

预备知识:
Springboot 2.0.6
Mybatis 3.4.6
Maven 3.5.3
Lomlok 1.16.18(可以参考:lombok 简化 Java 代码)
Mysql 5.1.47

代码地址:
博文只是列举核心操作步骤,需要自己实际操作。
https://github.com/Tojian/spring-treasure-box/tree/master/tao-springboot-mybatis

一、pom文件添加mybatis相关依赖

这里用到spring-boot-starter基础和spring-boot-starter-test用来做单元测试验证数据访问
引入连接mysql的必要依赖mysql-connector-java
引入整合MyBatis的核心依赖mybatis-spring-boot-starter
这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖

  <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>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>

二、利用mybatis generator插件生成代码

1.加入插件依赖

<plugin>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-maven-plugin</artifactId>
     <version>1.3.2</version>
     <configuration>
     <!--插件的位置文件-->
    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
    <overwrite>true</overwrite>
    <verbose>true</verbose>
   </configuration>
</plugin>

2.编写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>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="/Users/taojian/mvnjar/mysql/mysql-connector-java/5.1.29/mysql-connector-java-5.1.29.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/mytest" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.taojian.mybatis.bean" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.taojian.mybatis.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

3.配置启动插件


核心命令 :mybatis-generator:generate -e

4.启动自动生成代码

如图所示,红色方框即是生成后的代码,里面覆盖了常见的增删改查,避免重复的CRUD操作。

@repository是用来注解接口,如下图:这个注解是将接口UserMapper的一个实现类交给spring管理(在spring中有开启对@repository注解的扫描),当哪些地方需要用到这个实现类作为依赖时,就可以注入了.在mybatis注册到spring的时候,已经UserMapper变成了一个bean,所以不需要用@Repository也是可以的,但是为了规范还是加上@Repository。


@Repository
public interface UserMapper {

    int deleteByPrimaryKey(Integer userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

三、添加application.properties文件

配置文件请参考:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/


## Mybatis 配置
mybatis.typeAliasesPackage=com.taojian.mybatis.bean
mybatis.mapperLocations=classpath:mapping/*.xml

spring.datasource.url=jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

四、启动项

创建项目的TaoSpringbootMybatisApplication类

@SpringBootApplication
@MapperScan("com.taojian.mybatis.mapper")
public class TaoSpringbootMybatisApplication {

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

}

springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中
在启动类中添加对mapper包扫描@MapperScan,这个注解非常的关键,这个对应了项目中mapper(dao)所对应的包路径,容易出错。

原文地址:https://www.cnblogs.com/tojian/p/10213840.html

时间: 2024-08-14 09:59:31

Springboot系列之Springboot与Mybatis整合的相关文章

springboot同mybatis整合

springboot和mybatis整合有两种开发模式,首先要做的是配置好开发环境, 实现步骤: 在maven文件pom中配置: 1)SpringBoot同Mybatis整合的依赖. <dependency> <groupId>com.ruijc</groupId> <artifactId>spring-boot-starter-mybatis</artifactId> <version>3.2.2</version> &

springboot(三).springboot用最简单的方式整合mybatis

 Springboot整合mybatis 在众多的orm框架中,我使用最多的,最习惯的,也是目前使用最广泛的就是mybatis,接下来我们就去将springboot整合mybatis 对于springboot整合mybatis有好几种方法,在这里我们使用最简单,最方便的一种整合方式 在pom中添加以下依赖 在application.properties 中增加以下配置 #数据库连接本地 spring.datasource.url=jdbc:mysql://localhost:3306/sprin

spring-boot+mybatis整合简写

spring与mybatis整合,代码将变得非常优雅! 主要使用的jar包是mybatis-spring-boot-starter.jar,其maven依赖如下,加入到pom.xml文件中 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1&

Springboot系列1_什么是Springboot

.title { text-align: center } .todo { font-family: monospace; color: red } .done { color: green } .tag { background-color: #eee; font-family: monospace; padding: 2px; font-size: 80%; font-weight: normal } .timestamp { color: #bebebe } .timestamp-kwd

ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查)

在springmvc+spring+mybatis里整合ztree实现增删改查,上一篇已经写了demo,下面就只贴出各层实现功能的代码: Jsp页面实现功能的js代码如下: <script> //用于捕获分类编辑按钮的 click 事件,并且根据返回值确定是否允许进入名称编辑状态 function beforeEditName(treeId, treeNode) { var zTree = $.fn.zTree.getZTreeObj("treeDemo"); zTree.

springboot+shiro+redis(单机redis版)整合教程-续(添加动态角色权限控制)

相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(单机redis版)整合教程 3. springboot+shiro+redis(集群redis版)整合教程 参考此教程前请先阅读 2.springboot+shiro+redis(单机redis版)整合教程,此教程是在其基础上进行修改添加动态角色权限的. 本教程整合环境: java8 maven redis(单机) 开发工具: idea 版本: springboot 1.5.15.RE

补习系列(15)-springboot 分布式会话原理

目录 一.背景 二.SpringBoot 分布式会话 三.样例程序 四.原理进阶 A. 序列化 B. 会话代理 C. 数据老化 小结 一.背景 在 补习系列(3)-springboot 几种scope 一文中,笔者介绍过 Session的部分,如下: 对于服务器而言,Session 通常是存储在本地的,比如Tomcat 默认将Session 存储在内存(ConcurrentHashMap)中. 但随着网站的用户越来越多,Session所需的空间会越来越大,同时单机部署的 Web应用会出现性能瓶颈

SpringBoot系列——利用系统环境变量与配置文件的分支选择实现“智能部署”

前言 通过之前的博客:SpringBoot系列——jar包与war包的部署,我们已经知道了如果实现项目的简单部署,但项目部署的时候最烦的是什么?修改成发布环境对应的配置!数据库连接地址.Eureka注册中心地址.Redis服务地址等,部署环境不一样,打包的时候就要改成对应的配置:常用的环境有本地开发环境dev,本地测试环境dev-test,生产测试环境prod-test,生产环境prod: 开发的时候我们用dev,项目直接运行,不用改配置:发布本地测试环境的时候,打包之前我们要先改成对应配置:上

SpringBoot系列教程web篇之404、500异常页面配置

接着前面几篇web处理请求的博文,本文将说明,当出现异常的场景下,如404请求url不存在,,403无权,500服务器异常时,我们可以如何处理 原文友链: SpringBoot系列教程web篇之404.500异常页面配置 I. 环境搭建 首先得搭建一个web应用才有可能继续后续的测试,借助SpringBoot搭建一个web应用属于比较简单的活; 创建一个maven项目,pom文件如下 <parent> <groupId>org.springframework.boot</gr