1. 程式人生 > >mybatis->mybatis自動連線資料庫生成實體和dao

mybatis->mybatis自動連線資料庫生成實體和dao

本文用的是maven,idea15

Mabatis三劍客分別是:mybatis-generator、mybatis-plugin、mybatis-pagehelper

一、mybatis-generator

根據我們的資料庫自動生成pojo、dao和xml檔案  pojo裡面放的是跟資料庫欄位一一對應的物件、dao層是介面,供service使用,xml是這個dao層介面的實現,sql語句都寫在xml裡

1.引入mabatis-generator

pom.xml裡引入配置

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
          <encoding>UTF-8</encoding>
          <compilerArguments>
            <extdirs>${project.basedir}/src/main/webapp/WEB-INF/lib/</extdirs>
          </compilerArguments>
        </configuration>
</plugin>

引入generatorConfig.xml  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="datasource.properties"></properties>

    <!--指定特定資料庫的jdbc驅動jar包的位置-->
    <classPathEntry location="${db.driverLocation}"/>

    <context id="default" targetRuntime="MyBatis3">

        <!-- optional,旨在建立class時,對註釋進行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的資料庫連線 -->
        <jdbcConnection
                driverClass="${db.driverClassName}"
                connectionURL="${db.url}"
                userId="${db.username}"
                password="${db.password}">
        </jdbcConnection>


        <!-- 非必需,型別處理器,在資料庫型別和java型別之間的轉換控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在該專案下所在的路徑
        -->
        <!--<javaModelGenerator targetPackage="com.mmall.pojo" targetProject=".\src\main\java">-->
        <javaModelGenerator targetPackage="com.mmall.pojo" targetProject="./src/main/java">
            <!-- 是否允許子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否對model新增 建構函式 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否對類CHAR型別的列的資料進行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model物件是否 不可改變  即生成的Model物件不會有 setter方法,只有構造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper對映檔案生成所在的目錄 為每一個數據庫的表生成對應的SqlMap檔案 -->
        <!--<sqlMapGenerator targetPackage="mappers" targetProject=".\src\main\resources">-->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客戶端程式碼,生成易於使用的針對Model物件和XML配置檔案 的程式碼
                type="ANNOTATEDMAPPER",生成Java Model 和基於註解的Mapper物件
                type="MIXEDMAPPER",生成基於註解的Java Model 和相應的Mapper物件
                type="XMLMAPPER",生成SQLMap XML檔案和獨立的Mapper介面
        -->

        <!-- targetPackage:mapper介面dao生成的位置 -->
        <!--<javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject=".\src\main\java">-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject="./src/main/java">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>


        <table tableName="mmall_shipping" domainObjectName="Shipping" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_cart" domainObjectName="Cart" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_cart_item" domainObjectName="CartItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_order" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_order_item" domainObjectName="OrderItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_pay_info" domainObjectName="PayInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <columnOverride column="detail" jdbcType="VARCHAR" />
            <columnOverride column="sub_images" jdbcType="VARCHAR" />
        </table>
        <table tableName="mmall_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>


        <!-- mybatis外掛的搭建 -->
    </context>
</generatorConfiguration>

2.新建datasource.properties檔案,配置資料庫連線資訊(這裡配置本地資料庫)

這裡寫圖片描述

db.driverLocation=F:/IdeaProjects/mmall/src/main/tool/mysql-connector-java-5.1.6-bin.jar
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mmall?useUnicode=true&amp;characterEncoding=UTF-8
db.username=root
db.password=940724

配置完之後,就點選idea的左下角有個小按鈕,把右側的maven project按鈕調出來(右側已有的請忽略) 這裡寫圖片描述

  點選maven project,並選定外掛載入(雙擊就行) 這裡寫圖片描述  下方的控制檯,出現build success就是成功了,就會發現dao的包和pojo包會生成好了介面和資料物件實體類,以及生成一個mapper資料夾,裡面儲存著資料庫裡各個實體的xml檔案

注意mapper裡生成的資料夾,我在建立的時候把時間戳給加里了,如果要完美的用的話,需要把時間戳優化一下

把insert標籤下的#{createTime,jdbcType=TIMESTAMP}和#{updateTime,jdbcType=TIMESTAMP}改成now()

把update標籤下的#{updateTime,jdbcType=TIMESTAMP}改成now()

這個now()方法是資料庫自帶的函式,表示現在的時間

二、mybatis-plugin

我用的是idea15,如果其他版本不好用的,可以換成idea 15  這是一個能夠追蹤dao介面和mapper檔案裡xml的一個外掛

  • 提供Mapper介面與配置檔案中對應SQL的導航

  • 提供Mapper介面與配置檔案中對應SQL的導航

  • 編輯XML檔案時自動補全

  • 根據Mapper介面, 使用快捷鍵生成xml檔案及SQL標籤

  • ResultMap中的property支援自動補全,支援級聯(屬性A.屬性B.屬性C)

  • 快捷鍵生成@Param註解

  • XML中編輯SQL時, 括號自動補全

  • XML中編輯SQL時, 支援引數自動補全(基於@Param註解識別引數)

  • 自動檢查Mapper XML檔案中ID衝突

  • 自動檢查Mapper XML檔案中錯誤的屬性值

  • 支援Find Usage

  • 支援重構從命名

  • 支援別名

  • 自動生成ResultMap屬性

  • 快捷鍵: Option + Enter(Mac) | Alt + Enter(Windows)

效果:點選dao可以追蹤到xml,,同理點選xml的sql右邊小箭頭,可以追蹤到dao方法

這裡寫圖片描述

1、安裝外掛:

這裡寫圖片描述 然後重啟下idea

2.mybatis-plugin外掛破解

到這個網址去 https://github.com/myoss/profile/tree/master/idea/plugin/MybatisPlugin  你看到了一個Git倉庫,先clone下來,不會clone的down下來,記住路徑  接下來,你看到一堆版本,選擇你安裝的mybatis_plugin版本號,比如我的是IDEA15版本的,我安裝版本就是v2.64,進入v2.64你會看到一個com資料夾,牢牢記住這個資料夾有大作用

這裡寫圖片描述

點選如圖所示的右上角的fork,登入自己的github,登入之後,會發現右邊有個綠色的Dowload圖示,點選那個就可以下載別人的專案了 這裡寫圖片描述

(1) windows破解

首先你要找到mybatis_plus.jar的位置,位置一般在這裡  C:\Users\youname(你自己的文件).IntelliJIdea\config\plugins\mybatis_plus\lib  用winRAR開啟 這裡寫圖片描述  將下載好的破解,與plugin外掛壓縮包中的檔案更換,拖入壓縮包,更換就行 這裡寫圖片描述

重啟你的IDEA,完畢,破解搞定

(2)mac破解

使用find命令在你的使用者目錄下查詢mybatis_plus.jar這個檔案

find ~ -name "mybatis_plus.jar"
  • 1

OK,拿到一個地址,然後進去

cd /Users/XXXXX/Library/Application Support/IntelliJIdea15/mybatis_plus/lib
  • 1

看到了2個檔案

#建立一個資料夾
mkdir m
#進去 
cd m
#拷貝到m資料夾中 
cp ../mybatis_plus.jar .
#解壓jar包
jar xf mybatis_plus.jar 
#複製com資料夾到這裡   路徑根據你情況而定,版本號也根據你情況而定
cp -r ~/Workspace/github/mybatis_plus/idea/plugin/MybatisPlugin/v2.7\~v2.83/com .
#重新打為jar包
jar cf mybatis_plus.jar *
#複製到m的上層目錄
cp mybatis_plus.jar ../

重啟你的IDEA,完畢,破解搞定

三、Mybatis-pageHelper

是一個開源的分頁外掛(如下網址有外掛的全介紹) https://github.com/pagehelper/Mybatis-PageHelper  它的原理,是通過spring的AOP來實現的,這個外掛能在執行sql的時候,把相關的資料再執行一次

1.pom.xml裡新增依賴

<dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>4.1.0</version>
    </dependency>

    <dependency>
      <groupId>com.github.miemiedev</groupId>
      <artifactId>mybatis-paginator</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>com.github.jsqlparser</groupId>
      <artifactId>jsqlparser</artifactId>
      <version>0.9.4</version>
    </dependency>

2.在spring配置檔案裡新增配置

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:mappers/*Mapper.xml"/>

        <!-- 分頁外掛 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageHelper">
                    <property name="properties">
                        <value>
                            dialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>

    </bean>

注意不同資料庫的方言的使用

這樣三劍客就都配置OK了