SpringBoot學(xué)習(xí)--04SpringBoot整合Mybatis(上)(配置mybatis generator)

陸陸續(xù)續(xù)又忙了幾天,繼續(xù)寫(xiě)。

本篇仿照著優(yōu)秀的文章的書(shū)寫(xiě),加上自己的理解和踩過(guò)的坑,原文地址:http://m.itdecent.cn/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin

環(huán)境/版本一覽:

  • 開(kāi)發(fā)工具:eclipse
  • springboot: 2.0.1.RELEASE
  • jdk:1.8.0_40
  • maven:3.3.9

額外功能:

  • mybatis generator 自動(dòng)生成代碼插件

開(kāi)始搭建:

一.創(chuàng)建項(xiàng)目:

1、同樣如上文,創(chuàng)建SpringBoot項(xiàng)目(默認(rèn)為最新版),

image

2、填寫(xiě)項(xiàng)目的基礎(chǔ)信息,

image

3、選擇基礎(chǔ)的項(xiàng)目依賴包,可以以后手動(dòng)添加,

image

4、選擇finish,等待依賴包加載完成。

這是生成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>

    <groupId>com.luozhen</groupId>
    <artifactId>StudyForSpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>StudyForSpringBoot</name>
    <description>There are two kinds of life, one is burning, the other is rotten.</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <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>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </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>
    </dependencies>

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

這是生成的文件目錄,其中的配置文件application.properties可以根據(jù)自己的習(xí)慣選擇,使用properties或者yml文件,本項(xiàng)目使用的是yml配置文件,所以把原本application.properties刪除,創(chuàng)建一個(gè)application.yml文件,也可以直接 rename后綴名為yml

image

更改后:

image

二.配置mybatis及自動(dòng)生成代碼generate

mybatis配置有兩種,一種是注解版,在代碼中配置;另一種是xml版,搭配generate,可以靈活的動(dòng)態(tài)生成SQL,很方便的調(diào)整SQL.

此處我們講解的是xml版,搭配generate使用.

1.盡管我們?cè)谇懊鎰?chuàng)建項(xiàng)目的時(shí)候依賴了mybatis依賴包,但是我們還是要確認(rèn)下.如果前面沒(méi)有勾選,我們也可以手動(dòng)導(dǎo)入mybatis依賴包,在<dependencies>標(biāo)簽中寫(xiě)入一下代碼導(dǎo)入依賴,

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

2.接下來(lái)就是application.yml配置文件中添加相關(guān)的配置.

#端口號(hào)
server:
  port: 55555

#datasource
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    # 基本屬性
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false
    username: root
    password: 123456

#mybatis
mybatis:
  type-aliases-package: com.luozhen.entity
  mapper-locations: classpath:mybatis/mappers/*.xml

以上的就是配置文件的基礎(chǔ)配置,后續(xù)可加入詳細(xì)的內(nèi)容,同時(shí)需要注意#mybatis后面的配置需要對(duì)應(yīng)的文件包,以下為我的文件包,

image

很多文章上都寫(xiě)了需要mybatis-config.xml文件,但是你會(huì)發(fā)現(xiàn)其中的內(nèi)容會(huì)和application.yml的重復(fù),配置為數(shù)據(jù)庫(kù)的連接配置.SpringBoot會(huì)自動(dòng)加載,spring.datasource.*相關(guān)配置,數(shù)據(jù)源就會(huì)自動(dòng)注入到sqlSessionFactory中,sqlSessionFactory會(huì)自動(dòng)注入到Mapper中,對(duì)了你一切都不用管了,直接拿起來(lái)使用就行了。

4.到這里mybatis的配置就完成了,接下就是generate的配置.同樣,也是需要在pom.xml中導(dǎo)入依賴包,在<build><plugins></plugins></build>中添加依賴,

<!-- generator自動(dòng)生成代碼依賴包 -->
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.5</version>
        <configuration>
          <!-- 配置generatorConfig的位置 -->
          <configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile>
          <verbose>true</verbose>
          <overwrite>true</overwrite>
        </configuration>
        <executions>
          <execution>
            <id>Generate MyBatis Files</id>
            <goals>
              <goal>generate</goal>
            </goals>
            <phase>generate</phase>
            <configuration>
              <verbose>true</verbose>
              <overwrite>true</overwrite>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>MySQL</groupId>
            <artifactId>mysql-connector-Java</artifactId>
            <version>5.1.46</version>
          </dependency>
          <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
          </dependency>
          <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
          </dependency>
        </dependencies>
      </plugin>

5.配置generatorConfig.xml,內(nèi)容,

<?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>
  <context id="mysqlTables" targetRuntime="MyBatis3">
    <!-- 是否去除自動(dòng)生成的注釋 true:是 : false:否 -->
    <commentGenerator>
      <property name="suppressDate" value="false" />
      <property name="suppressAllComments" value="true" />
    </commentGenerator>
    <!-- 數(shù)據(jù)庫(kù)鏈接URL,用戶名、密碼 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false" userId="root" password="123456">
    </jdbcConnection>

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

    <!-- 生成model模型,對(duì)應(yīng)的包,存放位置可以指定具體的路徑,如/ProjectName/src,也可以使用MAVEN來(lái)自動(dòng)生成 -->
    <javaModelGenerator targetPackage="com.luozhen.entity" targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!--對(duì)應(yīng)的xml mapper文件 -->
    <sqlMapGenerator targetPackage="mybatis/mappers" targetProject="src/main/resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- 對(duì)應(yīng)的dao接口 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.luozhen.daos" targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>


    <!-- 要生成的表 tableName是數(shù)據(jù)庫(kù)中的表名或視圖名 domainObjectName是實(shí)體類(lèi)名(不生成Example(幫助類(lèi))類(lèi)) -->
    <table tableName="sys_department" domainObjectName="SysDepartment" enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">
    </table>

  </context>

</generatorConfiguration>

具體的參考配置可以查看:

http://m.itdecent.cn/p/e09d2370b796 Mybatis Generator最完整配置詳解

6.最后配置generator生成,F(xiàn)5刷新

項(xiàng)目 右鍵==>run as ==> maven bulid ==>彈出對(duì)話框 ==>在goals中輸入mybatis-generator:generate 或者 點(diǎn)擊select --》選擇你的mybatis插件 --》apply --》run,結(jié)果如下

image

搭建完成后的目錄及文件:

目錄:

image

我的數(shù)據(jù)庫(kù)表結(jié)構(gòu):

image

生成的實(shí)體,SysDepartment.java:

package com.luozhen.entity;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonFormat;

public class SysDepartment {
    private String id;

    private String name;

    private Date createdate;

    private String parentId;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Date getCreatedate() {
        return createdate;
    }

    public void setCreatedate(Date createdate) {
        this.createdate = createdate;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId == null ? null : parentId.trim();
    }
}

生成的mapper.xml,在resources/mybatis/mappers下:

<?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.luozhen.daos.SysDepartmentMapper">
  <resultMap id="BaseResultMap" type="com.luozhen.entity.SysDepartment">
    <id column="ID" jdbcType="VARCHAR" property="id" />
    <result column="NAME" jdbcType="VARCHAR" property="name" />
    <result column="CREATEDATE" jdbcType="TIMESTAMP" property="createdate" />
    <result column="PARENT_ID" jdbcType="VARCHAR" property="parentId" />
  </resultMap>
  <sql id="Base_Column_List">
    ID, NAME, CREATEDATE, PARENT_ID
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from sys_department
    where ID = #{id,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    delete from sys_department
    where ID = #{id,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.luozhen.entity.SysDepartment">
    insert into sys_department (ID, NAME, CREATEDATE, PARENT_ID)
    values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP}, 
      #{parentId,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.luozhen.entity.SysDepartment">
    insert into sys_department
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        ID,
      </if>
      <if test="name != null">
        NAME,
      </if>
      <if test="createdate != null">
        CREATEDATE,
      </if>
      <if test="parentId != null">
        PARENT_ID,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="createdate != null">
        #{createdate,jdbcType=TIMESTAMP},
      </if>
      <if test="parentId != null">
        #{parentId,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.luozhen.entity.SysDepartment">
    update sys_department
    <set>
      <if test="name != null">
        NAME = #{name,jdbcType=VARCHAR},
      </if>
      <if test="createdate != null">
        CREATEDATE = #{createdate,jdbcType=TIMESTAMP},
      </if>
      <if test="parentId != null">
        PARENT_ID = #{parentId,jdbcType=VARCHAR},
      </if>
    </set>
    where ID = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.luozhen.entity.SysDepartment">
    update sys_department
    set NAME = #{name,jdbcType=VARCHAR},
      CREATEDATE = #{createdate,jdbcType=TIMESTAMP},
      PARENT_ID = #{parentId,jdbcType=VARCHAR}
    where ID = #{id,jdbcType=VARCHAR}
  </update>

對(duì)應(yīng)的daos文件,SysDepartmentMapper.java:

package com.luozhen.daos;

import java.util.List;

import com.luozhen.entity.SysDepartment;

public interface SysDepartmentMapper {
    int deleteByPrimaryKey(String id);

    int insert(SysDepartment record);

    int insertSelective(SysDepartment record);

    SysDepartment selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(SysDepartment record);

    int updateByPrimaryKey(SysDepartment record);
  
}

使用:

已經(jīng)完成生成文件,現(xiàn)在我們要使用生成的文件,使用生成mapper.xml中SQL語(yǔ)句,有兩種方法,一種統(tǒng)一,一種分散,看你的個(gè)人習(xí)慣.

(1)統(tǒng)一

1.首先在你的啟動(dòng)類(lèi)中添加一個(gè)注解,注解的目錄為生成的dao類(lèi)文件目錄,如下

package com.luozhen;

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

@MapperScan("com.luozhen.daos")
@SpringBootApplication
public class StudyForSpringBootApplication {

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

2.xml文件中

image

id屬性必須與你dao類(lèi)文件中方法名相對(duì)應(yīng)

image

,其中有些坑,下篇文章詳解,

(2)分散.在dao類(lèi)文件上,每個(gè)添加@Mapper注解,其余相同.

image.png

剩下的使用步驟就不再詳解,請(qǐng)參考文章:

http://m.itdecent.cn/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin

無(wú)非就是SpringMVC的基礎(chǔ)架構(gòu),以上若有問(wèn)題可以在評(píng)論區(qū)提出,大家相互學(xué)習(xí).

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容