詳解在springboot中使用Mybatis Generator的兩種方式

這篇文章主要介紹了詳解在springboot中使用Mybatis Generator的兩種方式,本文將介紹到在springboot的項目中如何去配置和使用MBG以及MBG生成代碼的兩種方式,非常具有實用價值,需要的朋友可以參考下

介紹

Mybatis Generator(MBG)是Mybatis的一個代碼生成工具。MBG解決了對數據庫操作有最大影響的一些CRUD操作,很大程度上提升開發效率。如果需要聯合查詢仍然需要手寫sql。相信很多人都聽說過微服務,各個微服務之間是鬆耦合的。每個微服務僅關注於完成一件任務並很好地完成該任務。在一個微服務的開發過程中很可能只關注對單表的操作。所以MBG在開發過程中可以快速的生成代碼提升開發效率。

本文將說到在springboot的項目中如何去配置(XML形式和Java配置類形式)和使用MBG以及MBG生成代碼的兩種方式(XML形式和註解形式),在springboot中更推薦去使用註解的形式。

MBG配置

1.添加依賴

  <dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.5</version>
  </dependency>

2.XML配置

配置示例:在新建springboot項目的根目錄下創建mbg.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>
  <context id="DB2Tables" targetRuntime="MyBatis3">
    <commentGenerator>
       <!-- 是否自動去除生成註釋 true 不生成-->
      <property name="suppressAllComments" value="true"/>
      <!--生成的註釋包含時間戳-->
      <!-- <property name="suppressDate" value="true"/> -->
    </commentGenerator>  
    <!-- 數據庫連接信息 -->
    <jdbcConnection 
      driverClass="com.mysql.jdbc.Driver"
      connectionURL="jdbc:mysql://localhost:3306/definesys"
      userId="root"
      password="welcome1">
    </jdbcConnection> 
   
   <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer,爲 true時把JDBC DECIMAL 和
      NUMERIC 類型解析爲java.math.BigDecimal -->   
    <javaTypeResolver>
      <property name="forceBigDecimals" value="true"/>
    </javaTypeResolver>
    
    <!-- 實體類 bean 帶有get和set方法的bean -->
    <javaModelGenerator targetPackage="com.mgb.domain" targetProject="src/main/java">
     <property name="enableSubPackages" value="true" />
     <property name="trimStrings" value="true" />
    </javaModelGenerator>
  
  <!-- sql語句相關的xml或者註解的生成包路徑 -->
    <sqlMapGenerator targetPackage="com.mgb.mapper" targetProject="src/main/java">
     <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
  
  <!-- 生成的接口所在的位置 註解type="ANNOTATEDMAPPER" xml type="XMLMAPPER" -->  
    <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.mgb.dao" targetProject="src/main/java">
     <property name="enableSubPackages" value="true" />
    </javaClientGenerator> 
     
    <table tableName="user_info" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
      <property name="constructorBased" value="false" />
      <!-- 數據庫表主鍵 -->
      <generatedKey column="id" sqlStatement="JDBC" identity="true" />
    </table>
  </context>
</generatorConfiguration>

配置詳解

<?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>
<!-- 可以用於加載配置項或者配置文件,在整個配置文件中就可以使用${propertyKey}的方式來引用配置項
  resource:配置資源加載地址,使用resource,MBG從classpath開始找,比如com/myproject/generatorConfig.properties    
  url:配置資源加載地質,使用URL的方式,比如file:///C:/myfolder/generatorConfig.properties.
  注意,兩個屬性只能選址一個;

  另外,如果使用了mybatis-generator-maven-plugin,那麼在pom.xml中定義的properties都可以直接在generatorConfig.xml中使用
<properties resource="" url="" />
 -->

 <!-- 在MBG工作的時候,需要額外加載的依賴包
   location屬性指明加載jar/zip包的全路徑
<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />
 -->

<!-- 
  context:生成一組對象的環境 
  id:必選,上下文id,用於在生成錯誤時提示
  defaultModelType:指定生成對象的樣式
    1,conditional:類似hierarchical;
    2,flat:所有內容(主鍵,blob)等全部生成在一個對象中;
    3,hierarchical:主鍵生成一個XXKey對象(key class),Blob等單獨生成一個對象,其他簡單屬性在一個對象中(record class)
  targetRuntime:
    1,MyBatis3:默認的值,生成基於MyBatis3.x以上版本的內容,包括XXXBySample;
    2,MyBatis3Simple:類似MyBatis3,只是不生成XXXBySample;
  introspectedColumnImpl:類全限定名,用於擴展MBG
-->
 <context id="mysql" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple" >

  <!-- 自動識別數據庫關鍵字,默認false,如果設置爲true,根據SqlReservedWords中定義的關鍵字列表;
    一般保留默認值,遇到數據庫關鍵字(Java關鍵字),使用columnOverride覆蓋
   -->
  <property name="autoDelimitKeywords" value="false"/>
  <!-- 生成的Java文件的編碼 -->
  <property name="javaFileEncoding" value="UTF-8"/>
  <!-- 格式化java代碼 -->
  <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
  <!-- 格式化XML代碼 -->
  <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>

  <!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,比如ORACLE就是雙引號,MYSQL默認是`反引號; -->
  <property name="beginningDelimiter" value="`"/>
  <property name="endingDelimiter" value="`"/>

  <!-- 必須要有的,使用這個配置鏈接數據庫
    @TODO:是否可以擴展
   -->
  <jdbcConnection driver connectionURL="jdbc:mysql:///pss" userId="root" password="admin">
    <!-- 這裏面可以設置property屬性,每一個property屬性都設置到配置的Driver上 -->
  </jdbcConnection>

  <!-- java類型處理器 
    用於處理DB中的類型到Java中的類型,默認使用JavaTypeResolverDefaultImpl;
    注意一點,默認會先嚐試使用Integer,Long,Short等來對應DECIMAL和 NUMERIC數據類型; 
  -->
  <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
    <!-- 
      true:使用BigDecimal對應DECIMAL和 NUMERIC數據類型
      false:默認,
        scale>0;length>18:使用BigDecimal;
        scale=0;length[10,18]:使用Long;
        scale=0;length[5,9]:使用Integer;
        scale=0;length<5:使用Short;
     -->
    <property name="forceBigDecimals" value="false"/>
  </javaTypeResolver>

  <!-- java模型創建器,是必須要的元素
    負責:1,key類(見context的defaultModelType);2,java類;3,查詢類
    targetPackage:生成的類要放的包,真實的包受enableSubPackages屬性控制;
    targetProject:目標項目,指定一個存在的目錄下,生成的內容會放到指定目錄中,如果目錄不存在,MBG不會自動建目錄
   -->
  <javaModelGenerator targetPackage="com._520it.mybatis.domain" targetProject="src/main/java">
    <!-- for MyBatis3/MyBatis3Simple
      自動爲每一個生成的類創建一個構造方法,構造方法包含了所有的field;而不是使用setter;
     -->
    <property name="constructorBased" value="false"/>

    <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
    <property name="enableSubPackages" value="true"/>

    <!-- for MyBatis3 / MyBatis3Simple
      是否創建一個不可變的類,如果爲true,
      那麼MBG會創建一個沒有setter方法的類,取而代之的是類似constructorBased的類
     -->
    <property name="immutable" value="false"/>

    <!-- 設置一個根對象,
      如果設置了這個根對象,那麼生成的keyClass或者recordClass會繼承這個類;在Table的rootClass屬性中可以覆蓋該選項
      注意:如果在key class或者record class中有root class相同的屬性,MBG就不會重新生成這些屬性了,包括:
        1,屬性名相同,類型相同,有相同的getter/setter方法;
     -->
    <property name="rootClass" value="com._520it.mybatis.domain.BaseDomain"/>

    <!-- 設置是否在getter方法中,對String類型字段調用trim()方法 -->
    <property name="trimStrings" value="true"/>
  </javaModelGenerator>

  <!-- 生成SQL map的XML文件生成器,
    注意,在Mybatis3之後,我們可以使用mapper.xml文件+Mapper接口(或者不用mapper接口),
      或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的話,這個元素就必須配置
    targetPackage/targetProject:同javaModelGenerator
   -->
  <sqlMapGenerator targetPackage="com._520it.mybatis.mapper" targetProject="src/main/resources">
    <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
    <property name="enableSubPackages" value="true"/>
  </sqlMapGenerator>

  <!-- 對於mybatis來說,即生成Mapper接口,注意,如果沒有配置該元素,那麼默認不會生成Mapper接口 
    targetPackage/targetProject:同javaModelGenerator
    type:選擇怎麼生成mapper接口(在MyBatis3/MyBatis3Simple下):
      1,ANNOTATEDMAPPER:會生成使用Mapper接口+Annotation的方式創建(SQL生成在annotation中),不會生成對應的XML;
      2,MIXEDMAPPER:使用混合配置,會生成Mapper接口,並適當添加合適的Annotation,但是XML會生成在XML中;
      3,XMLMAPPER:會生成Mapper接口,接口完全依賴XML;
    注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
  -->
  <javaClientGenerator targetPackage="com._520it.mybatis.mapper" type="ANNOTATEDMAPPER" targetProject="src/main/java">
    <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
    <property name="enableSubPackages" value="true"/>
    <!-- 可以爲所有生成的接口添加一個父接口,但是MBG只負責生成,不負責檢查
    <property name="rootInterface" value=""/>
     -->
  </javaClientGenerator>
  <!-- 選擇一個table來生成相關文件,可以有一個或多個table,必須要有table元素
    選擇的table會生成一下文件:
    1,SQL map文件
    2,生成一個主鍵類;
    3,除了BLOB和主鍵的其他字段的類;
    4,包含BLOB的類;
    5,一個用戶生成動態查詢的條件類(selectByExample, deleteByExample),可選;
    6,Mapper接口(可選)

    tableName(必要):要生成對象的表名;
    注意:大小寫敏感問題。正常情況下,MBG會自動的去識別數據庫標識符的大小寫敏感度,在一般情況下,MBG會
      根據設置的schema,catalog或tablename去查詢數據表,按照下面的流程:
      1,如果schema,catalog或tablename中有空格,那麼設置的是什麼格式,就精確的使用指定的大小寫格式去查詢;
      2,否則,如果數據庫的標識符使用大寫的,那麼MBG自動把表名變成大寫再查找;
      3,否則,如果數據庫的標識符使用小寫的,那麼MBG自動把表名變成小寫再查找;
      4,否則,使用指定的大小寫格式查詢;
    另外的,如果在創建表的時候,使用的""把數據庫對象規定大小寫,就算數據庫標識符是使用的大寫,在這種情況下也會使用給定的大小寫來創建表名;
    這個時候,請設置delimitIdentifiers="true"即可保留大小寫格式;

    可選:
    1,schema:數據庫的schema;
    2,catalog:數據庫的catalog;
    3,alias:爲數據表設置的別名,如果設置了alias,那麼生成的所有的SELECT SQL語句中,列名會變成:alias_actualColumnName
    4,domainObjectName:生成的domain類的名字,如果不設置,直接使用表名作爲domain類的名字;可以設置爲somepck.domainName,那麼會自動把domainName類再放到somepck包裏面;
    5,enableInsert(默認true):指定是否生成insert語句;
    6,enableSelectByPrimaryKey(默認true):指定是否生成按照主鍵查詢對象的語句(就是getById或get);
    7,enableSelectByExample(默認true):MyBatis3Simple爲false,指定是否生成動態查詢語句;
    8,enableUpdateByPrimaryKey(默認true):指定是否生成按照主鍵修改對象的語句(即update);
    9,enableDeleteByPrimaryKey(默認true):指定是否生成按照主鍵刪除對象的語句(即delete);
    10,enableDeleteByExample(默認true):MyBatis3Simple爲false,指定是否生成動態刪除語句;
    11,enableCountByExample(默認true):MyBatis3Simple爲false,指定是否生成動態查詢總條數語句(用於分頁的總條數查詢);
    12,enableUpdateByExample(默認true):MyBatis3Simple爲false,指定是否生成動態修改語句(只修改對象中不爲空的屬性);
    13,modelType:參考context元素的defaultModelType,相當於覆蓋;
    14,delimitIdentifiers:參考tableName的解釋,注意,默認的delimitIdentifiers是雙引號,如果類似MYSQL這樣的數據庫,使用的是`(反引號,那麼還需要設置context的beginningDelimiter和endingDelimiter屬性)
    15,delimitAllColumns:設置是否所有生成的SQL中的列名都使用標識符引起來。默認爲false,delimitIdentifiers參考context的屬性

    注意,table裏面很多參數都是對javaModelGenerator,context等元素的默認屬性的一個複寫;
   -->
  <table tableName="userinfo" >

    <!-- 參考 javaModelGenerator 的 constructorBased屬性-->
    <property name="constructorBased" value="false"/>

    <!-- 默認爲false,如果設置爲true,在生成的SQL中,table名字不會加上catalog或schema; -->
    <property name="ignoreQualifiersAtRuntime" value="false"/>

    <!-- 參考 javaModelGenerator 的 immutable 屬性 -->
    <property name="immutable" value="false"/>

    <!-- 指定是否只生成domain類,如果設置爲true,只生成domain類,如果還配置了sqlMapGenerator,那麼在mapper XML文件中,只生成resultMap元素 -->
    <property name="modelOnly" value="false"/>

    <!-- 參考 javaModelGenerator 的 rootClass 屬性 
    <property name="rootClass" value=""/>
     -->

    <!-- 參考javaClientGenerator 的 rootInterface 屬性
    <property name="rootInterface" value=""/>
    -->

    <!-- 如果設置了runtimeCatalog,那麼在生成的SQL中,使用該指定的catalog,而不是table元素上的catalog 
    <property name="runtimeCatalog" value=""/>
    -->

    <!-- 如果設置了runtimeSchema,那麼在生成的SQL中,使用該指定的schema,而不是table元素上的schema 
    <property name="runtimeSchema" value=""/>
    -->

    <!-- 如果設置了runtimeTableName,那麼在生成的SQL中,使用該指定的tablename,而不是table元素上的tablename 
    <property name="runtimeTableName" value=""/>
    -->
    <!-- 注意,該屬性只針對MyBatis3Simple有用;
      如果選擇的runtime是MyBatis3Simple,那麼會生成一個SelectAll方法,如果指定了selectAllOrderByClause,那麼會在該SQL中添加指定的這個order條件;
     -->
    <property name="selectAllOrderByClause" value="age desc,username asc"/>

    <!-- 如果設置爲true,生成的model類會直接使用column本身的名字,而不會再使用駝峯命名方法,比如BORN_DATE,生成的屬性名字就是BORN_DATE,而不會是bornDate -->
    <property name="useActualColumnNames" value="false"/>

    <!-- generatedKey用於生成生成主鍵的方法,
      如果設置了該元素,MBG會在生成的<insert>元素中生成一條正確的<selectKey>元素,該元素可選
      column:主鍵的列名;
      sqlStatement:要生成的selectKey語句,有以下可選項:
        Cloudscape:相當於selectKey的SQL爲: VALUES IDENTITY_VAL_LOCAL()
        DB2    :相當於selectKey的SQL爲: VALUES IDENTITY_VAL_LOCAL()
        DB2_MF  :相當於selectKey的SQL爲:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
        Derby   :相當於selectKey的SQL爲:VALUES IDENTITY_VAL_LOCAL()
        HSQLDB   :相當於selectKey的SQL爲:CALL IDENTITY()
        Informix :相當於selectKey的SQL爲:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
        MySql   :相當於selectKey的SQL爲:SELECT LAST_INSERT_ID()
        SqlServer :相當於selectKey的SQL爲:SELECT SCOPE_IDENTITY()
        SYBASE   :相當於selectKey的SQL爲:SELECT @@IDENTITY
        JDBC   :相當於在生成的insert元素上添加useGeneratedKeys="true"和keyProperty屬性
    <generatedKey column="" sqlStatement=""/>
     -->

    <!-- 
      該元素會在根據表中列名計算對象屬性名之前先重命名列名,非常適合用於表中的列都有公用的前綴字符串的時候,
      比如列名爲:CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS等;
      那麼就可以設置searchString爲"^CUST_",並使用空白替換,那麼生成的Customer對象中的屬性名稱就不是
      custId,custName等,而是先被替換爲ID,NAME,EMAIL,然後變成屬性:id,name,email;

      注意,MBG是使用java.util.regex.Matcher.replaceAll來替換searchString和replaceString的,
      如果使用了columnOverride元素,該屬性無效;

    <columnRenamingRule searchString="" replaceString=""/>
     -->

     <!-- 用來修改表中某個列的屬性,MBG會使用修改後的列來生成domain的屬性;
       column:要重新設置的列名;
       注意,一個table元素中可以有多個columnOverride元素哈~
     -->
        <!-- 指定類型 -->
     <columnOverride column="RECORD_DATE" jdbcType="TIMESTAMP"/> 

     <columnOverride column="username">
       <!-- 使用property屬性來指定列要生成的屬性名稱 -->
       <property name="property" value="userName"/>

       <!-- javaType用於指定生成的domain的屬性類型,使用類型的全限定名
       <property name="javaType" value=""/>
       -->

       <!-- jdbcType用於指定該列的JDBC類型 
       <property name="jdbcType" value=""/>
       -->

       <!-- typeHandler 用於指定該列使用到的TypeHandler,如果要指定,配置類型處理器的全限定名
         注意,mybatis中,不會生成到mybatis-config.xml中的typeHandler
         只會生成類似:where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler}的參數描述
       <property name="jdbcType" value=""/>
       -->

       <!-- 參考table元素的delimitAllColumns配置,默認爲false
       <property name="delimitedColumnName" value=""/>
       -->
     </columnOverride>

     <!-- ignoreColumn設置一個MGB忽略的列,如果設置了改列,那麼在生成的domain中,生成的SQL中,都不會有該列出現 
       column:指定要忽略的列的名字;
       delimitedColumnName:參考table元素的delimitAllColumns配置,默認爲false

       注意,一個table元素中可以有多個ignoreColumn元素
     <ignoreColumn column="deptId" delimitedColumnName=""/>
     -->
  </table>
</context>
</generatorConfiguration>

生成代碼:

public class TestMGB {
  public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
    List<String> warnings =new ArrayList<String>();
    boolean overwrite=true;
    File configFile=new File("mgb.xml");
    ConfigurationParser cp=new ConfigurationParser(warnings);
    Configuration config=cp.parseConfiguration(configFile);
    DefaultShellCallback callback=new DefaultShellCallback(overwrite);
    MyBatisGenerator myBatisGenerator=new MyBatisGenerator(config,callback,warnings);
    myBatisGenerator.generate(null);
  }

}

3.Java配置示例

基於Java的配置是和上面的XML配置是相對應的。直接運行該示例即可生成數據表對於的pojo,mapper接口和一個sqlprovider Java類。

package com.mgb.test;

import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.CommentGeneratorConfiguration;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.JDBCConnectionConfiguration;
import org.mybatis.generator.config.JavaClientGeneratorConfiguration;
import org.mybatis.generator.config.JavaModelGeneratorConfiguration;
import org.mybatis.generator.config.JavaTypeResolverConfiguration;
import org.mybatis.generator.config.ModelType;
import org.mybatis.generator.config.PluginConfiguration;
import org.mybatis.generator.config.SqlMapGeneratorConfiguration;
import org.mybatis.generator.config.TableConfiguration;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MGBConfig {
  public static void main(String[] args) throws Exception{
     //配置xml配置項
     List<String> warnings = new ArrayList<String>();
     boolean overwrite = true;
     Configuration config = new Configuration();
     Context context = new Context(ModelType.CONDITIONAL);
     context.setTargetRuntime("MyBatis3");
     context.setId("defaultContext");
     
    //自動識別數據庫關鍵字,默認false,如果設置爲true,
    //根據SqlReservedWords中定義的關鍵字列表;一般保留默認值,遇到數據庫關鍵字(Java關鍵字),
    //使用columnOverride覆蓋
     context.addProperty("autoDelimitKeywords","true");
     
    //生成的Java文件的編碼
    context.addProperty("javaFileEncoding","utf-8");
    context.addProperty("beginningDelimiter","`");
    context.addProperty("endingDelimiter","`");
    //格式化java代碼
    context.addProperty("javaFormatter","org.mybatis.generator.api.dom.DefaultJavaFormatter");
    //格式化xml代碼
    context.addProperty("xmlFormatter","org.mybatis.generator.api.dom.DefaultXmlFormatter");
    //格式化信息
    PluginConfiguration pluginConfiguration = new PluginConfiguration();
    pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.SerializablePlugin");
    pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.ToStringPlugin");
    context.addPluginConfiguration(pluginConfiguration);
    
    //設置是否去除生成註釋
    CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();
    commentGeneratorConfiguration.addProperty("suppressAllComments","true");
    //commentGeneratorConfiguration.addProperty("suppressDate","true");
    context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);
  
    //設置連接數據庫
    JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
    jdbcConnectionConfiguration.setDriverClass("com.mysql.jdbc.Driver");
    jdbcConnectionConfiguration.setConnectionURL("jdbc:mysql://localhost:3306/definesys");
    jdbcConnectionConfiguration.setPassword("welcome1");
    jdbcConnectionConfiguration.setUserId("root");
    context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);
    
    JavaTypeResolverConfiguration javaTypeResolverConfiguration = new JavaTypeResolverConfiguration();
    //是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.)
    javaTypeResolverConfiguration.addProperty("forceBigDecimals","false");
    context.setJavaTypeResolverConfiguration(javaTypeResolverConfiguration);
    
    //生成實體類的地址
    JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
    javaModelGeneratorConfiguration.setTargetPackage("com.mgb.domain");
    javaModelGeneratorConfiguration.setTargetProject("src/main/java");
    javaModelGeneratorConfiguration.addProperty("enableSubPackages","true");
    javaModelGeneratorConfiguration.addProperty("trimStrings","true");
    context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);
    
    //生成的xml的地址
    SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
    sqlMapGeneratorConfiguration.setTargetProject("src/main/java");
    sqlMapGeneratorConfiguration.setTargetPackage("com.mgb.mapper");
    sqlMapGeneratorConfiguration.addProperty("enableSubPackages","true");
    context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
    
    //生成註解接口
    JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
    javaClientGeneratorConfiguration.setTargetPackage("com.mgb.dao");
    javaClientGeneratorConfiguration.setTargetProject("src/main/java");
    //註解形式 ANNOTATEDMAPPER xml形式 XMLMAPPER
    javaClientGeneratorConfiguration.setConfigurationType("ANNOTATEDMAPPER");
    javaClientGeneratorConfiguration.addProperty("enableSubPackages","true");
    context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
    
    TableConfiguration tableConfiguration = new TableConfiguration(context);
    tableConfiguration.setTableName("user_info");
    tableConfiguration.setCountByExampleStatementEnabled(true);
    tableConfiguration.setUpdateByExampleStatementEnabled(true);
    tableConfiguration.setDeleteByExampleStatementEnabled(true);
    tableConfiguration.setInsertStatementEnabled(true);
    tableConfiguration.setDeleteByPrimaryKeyStatementEnabled(true);    
    context.addTableConfiguration(tableConfiguration);
    
    config.addContext(context);
    DefaultShellCallback callback = new DefaultShellCallback(overwrite);
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
    myBatisGenerator.generate(null);
  }  
}

使用

package com.mgb.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mgb.dao.UserInfoMapper;
import com.mgb.domain.UserInfo;
import com.mgb.domain.UserInfoExample;

@Service
public class UserService {
  @Autowired
  private UserInfoMapper userInfoMapper;
  
  /**
   * 按姓名查詢
   * @param name
   * @return
   */
  public List<UserInfo> getUserByName(String name){
    UserInfoExample uerInfoExample=new UserInfoExample();
    uerInfoExample.createCriteria().andNameEqualTo(name);
    return userInfoMapper.selectByExample(uerInfoExample);
  }
  
  /**
   * 有條件的insert
   * @param userInfo
   * @return
   */
  public Integer addUser(UserInfo userInfo) {
    return userInfoMapper.insertSelective(userInfo);
  }
  
  /**
   * 根據ID更新用戶信息
   * @param userInfo
   * @return
   */
  public Integer updateUser(UserInfo userInfo) {
    return userInfoMapper.updateByPrimaryKey(userInfo);
  }
  
  /**
   * 根據ID刪除用戶
   * @param id
   * @return
   */
  public Integer deleteUserById(Integer id) {
    return userInfoMapper.deleteByPrimaryKey(id);
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章