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

陸陸續(xù)續(xù)又忙了幾天,繼續(xù)寫般哼。

本篇仿照著優(yōu)秀的文章的書寫宛蚓,加上自己的理解和踩過的坑洲押,原文地址:http://www.reibang.com/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin

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

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

額外功能:

  • mybatis generator 自動生成代碼插件

開始搭建:

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

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

image

2、填寫項目的基礎(chǔ)信息悟泵,

image

3杈笔、選擇基礎(chǔ)的項目依賴包,可以以后手動添加魁袜,

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文件店量,本項目使用的是yml配置文件,所以把原本application.properties刪除鞠呈,創(chuàng)建一個application.yml文件,也可以直接 rename后綴名為yml

image

更改后:

image

二.配置mybatis及自動生成代碼generate

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

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

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

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

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

#端口號
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)容,同時需要注意#mybatis后面的配置需要對應(yīng)的文件包,以下為我的文件包,

image

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

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

<!-- generator自動生成代碼依賴包 -->
      <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">
    <!-- 是否去除自動生成的注釋 true:是 : false:否 -->
    <commentGenerator>
      <property name="suppressDate" value="false" />
      <property name="suppressAllComments" value="true" />
    </commentGenerator>
    <!-- 數(shù)據(jù)庫鏈接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模型蜒蕾,對應(yīng)的包介牙,存放位置可以指定具體的路徑,如/ProjectName/src,也可以使用MAVEN來自動生成 -->
    <javaModelGenerator targetPackage="com.luozhen.entity" targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

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

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


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

  </context>

</generatorConfiguration>

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

http://www.reibang.com/p/e09d2370b796 Mybatis Generator最完整配置詳解

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

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

image

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

目錄:

image

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

image

生成的實體,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>

對應(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語句,有兩種方法,一種統(tǒng)一,一種分散,看你的個人習(xí)慣.

(1)統(tǒng)一

1.首先在你的啟動類中添加一個注解,注解的目錄為生成的dao類文件目錄,如下

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類文件中方法名相對應(yīng)

image

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

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

image.png

剩下的使用步驟就不再詳解,請參考文章:

http://www.reibang.com/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市桑孩,隨后出現(xiàn)的幾起案子拜鹤,更是在濱河造成了極大的恐慌,老刑警劉巖流椒,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件敏簿,死亡現(xiàn)場離奇詭異,居然都是意外死亡宣虾,警方通過查閱死者的電腦和手機(jī)惯裕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來安岂,“玉大人轻猖,你說我怎么就攤上這事∮蚰牵” “怎么了咙边?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長次员。 經(jīng)常有香客問我败许,道長,這世上最難降的妖魔是什么淑蔚? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任市殷,我火速辦了婚禮,結(jié)果婚禮上刹衫,老公的妹妹穿的比我還像新娘醋寝。我一直安慰自己,他們只是感情好带迟,可當(dāng)我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布音羞。 她就那樣靜靜地躺著,像睡著了一般仓犬。 火紅的嫁衣襯著肌膚如雪嗅绰。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天搀继,我揣著相機(jī)與錄音窘面,去河邊找鬼。 笑死叽躯,一個胖子當(dāng)著我的面吹牛财边,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播点骑,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼酣难,長吁一口氣:“原來是場噩夢啊……” “哼们童!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起鲸鹦,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎跷跪,沒想到半個月后馋嗜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡吵瞻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年葛菇,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片橡羞。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡眯停,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出卿泽,到底是詐尸還是另有隱情莺债,我是刑警寧澤,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布签夭,位于F島的核電站齐邦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏第租。R本人自食惡果不足惜措拇,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望慎宾。 院中可真熱鬧丐吓,春花似錦、人聲如沸趟据。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽之宿。三九已至族操,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間比被,已是汗流浹背色难。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留等缀,地道東北人枷莉。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像尺迂,于是被迫代替她去往敵國和親笤妙。 傳聞我的和親對象是個殘疾皇子冒掌,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,747評論 2 361

推薦閱讀更多精彩內(nèi)容