1. 程式人生 > >Springboot系列之Springboot與Mybatis整合

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)所對應的包路徑,容易出錯。