麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發(fā) > Java > 正文

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

2024-07-14 08:42:52
字體:
供稿:網(wǎng)友

介紹

Mybatis Generator(MBG)是Mybatis的一個(gè)代碼生成工具。MBG解決了對(duì)數(shù)據(jù)庫操作有最大影響的一些CRUD操作,很大程度上提升開發(fā)效率。如果需要聯(lián)合查詢?nèi)匀恍枰謱憇ql。相信很多人都聽說過微服務(wù),各個(gè)微服務(wù)之間是松耦合的。每個(gè)微服務(wù)僅關(guān)注于完成一件任務(wù)并很好地完成該任務(wù)。在一個(gè)微服務(wù)的開發(fā)過程中很可能只關(guān)注對(duì)單表的操作。所以MBG在開發(fā)過程中可以快速的生成代碼提升開發(fā)效率。

本文將說到在springboot的項(xiàng)目中如何去配置(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項(xiàng)目的根目錄下創(chuàng)建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>       <!-- 是否自動(dòng)去除生成注釋 true 不生成-->      <property name="suppressAllComments" value="true"/>      <!--生成的注釋包含時(shí)間戳-->      <!-- <property name="suppressDate" value="true"/> -->    </commentGenerator>      <!-- 數(shù)據(jù)庫連接信息 -->    <jdbcConnection       driverClass="com.mysql.jdbc.Driver"      connectionURL="jdbc:mysql://localhost:3306/definesys"      userId="root"      password="welcome1">    </jdbcConnection>       <!-- 默認(rèn)false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時(shí)把JDBC DECIMAL 和      NUMERIC 類型解析為java.math.BigDecimal -->       <javaTypeResolver>      <property name="forceBigDecimals" value="true"/>    </javaTypeResolver>        <!-- 實(shí)體類 bean 帶有g(shù)et和set方法的bean -->    <javaModelGenerator targetPackage="com.mgb.domain" targetProject="src/main/java">     <property name="enableSubPackages" value="true" />     <property name="trimStrings" value="true" />    </javaModelGenerator>    <!-- sql語句相關(guān)的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" />      <!-- 數(shù)據(jù)庫表主鍵 -->      <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><!-- 可以用于加載配置項(xiàng)或者配置文件,在整個(gè)配置文件中就可以使用${propertyKey}的方式來引用配置項(xiàng)  resource:配置資源加載地址,使用resource,MBG從classpath開始找,比如com/myproject/generatorConfig.properties      url:配置資源加載地質(zhì),使用URL的方式,比如file:///C:/myfolder/generatorConfig.properties.  注意,兩個(gè)屬性只能選址一個(gè);  另外,如果使用了mybatis-generator-maven-plugin,那么在pom.xml中定義的properties都可以直接在generatorConfig.xml中使用<properties resource="" url="" /> --> <!-- 在MBG工作的時(shí)候,需要額外加載的依賴包   location屬性指明加載jar/zip包的全路徑<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --><!--   context:生成一組對(duì)象的環(huán)境   id:必選,上下文id,用于在生成錯(cuò)誤時(shí)提示  defaultModelType:指定生成對(duì)象的樣式    1,conditional:類似hierarchical;    2,flat:所有內(nèi)容(主鍵,blob)等全部生成在一個(gè)對(duì)象中;    3,hierarchical:主鍵生成一個(gè)XXKey對(duì)象(key class),Blob等單獨(dú)生成一個(gè)對(duì)象,其他簡單屬性在一個(gè)對(duì)象中(record class)  targetRuntime:    1,MyBatis3:默認(rèn)的值,生成基于MyBatis3.x以上版本的內(nèi)容,包括XXXBySample;    2,MyBatis3Simple:類似MyBatis3,只是不生成XXXBySample;  introspectedColumnImpl:類全限定名,用于擴(kuò)展MBG--> <context id="mysql" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple" >  <!-- 自動(dòng)識(shí)別數(shù)據(jù)庫關(guān)鍵字,默認(rèn)false,如果設(shè)置為true,根據(jù)SqlReservedWords中定義的關(guān)鍵字列表;    一般保留默認(rèn)值,遇到數(shù)據(jù)庫關(guān)鍵字(Java關(guān)鍵字),使用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:指明數(shù)據(jù)庫的用于標(biāo)記數(shù)據(jù)庫對(duì)象名的符號(hào),比如ORACLE就是雙引號(hào),MYSQL默認(rèn)是`反引號(hào); -->  <property name="beginningDelimiter" value="`"/>  <property name="endingDelimiter" value="`"/>  <!-- 必須要有的,使用這個(gè)配置鏈接數(shù)據(jù)庫    @TODO:是否可以擴(kuò)展   -->  <jdbcConnection driver connectionURL="jdbc:mysql:///pss" userId="root" password="admin">    <!-- 這里面可以設(shè)置property屬性,每一個(gè)property屬性都設(shè)置到配置的Driver上 -->  </jdbcConnection>  <!-- java類型處理器     用于處理DB中的類型到Java中的類型,默認(rèn)使用JavaTypeResolverDefaultImpl;    注意一點(diǎn),默認(rèn)會(huì)先嘗試使用Integer,Long,Short等來對(duì)應(yīng)DECIMAL和 NUMERIC數(shù)據(jù)類型;   -->  <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">    <!--       true:使用BigDecimal對(duì)應(yīng)DECIMAL和 NUMERIC數(shù)據(jù)類型      false:默認(rèn),        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模型創(chuàng)建器,是必須要的元素    負(fù)責(zé):1,key類(見context的defaultModelType);2,java類;3,查詢類    targetPackage:生成的類要放的包,真實(shí)的包受enableSubPackages屬性控制;    targetProject:目標(biāo)項(xiàng)目,指定一個(gè)存在的目錄下,生成的內(nèi)容會(huì)放到指定目錄中,如果目錄不存在,MBG不會(huì)自動(dòng)建目錄   -->  <javaModelGenerator targetPackage="com._520it.mybatis.domain" targetProject="src/main/java">    <!-- for MyBatis3/MyBatis3Simple      自動(dòng)為每一個(gè)生成的類創(chuàng)建一個(gè)構(gòu)造方法,構(gòu)造方法包含了所有的field;而不是使用setter;     -->    <property name="constructorBased" value="false"/>    <!-- 在targetPackage的基礎(chǔ)上,根據(jù)數(shù)據(jù)庫的schema再生成一層package,最終生成的類放在這個(gè)package下,默認(rèn)為false -->    <property name="enableSubPackages" value="true"/>    <!-- for MyBatis3 / MyBatis3Simple      是否創(chuàng)建一個(gè)不可變的類,如果為true,      那么MBG會(huì)創(chuàng)建一個(gè)沒有setter方法的類,取而代之的是類似constructorBased的類     -->    <property name="immutable" value="false"/>    <!-- 設(shè)置一個(gè)根對(duì)象,      如果設(shè)置了這個(gè)根對(duì)象,那么生成的keyClass或者recordClass會(huì)繼承這個(gè)類;在Table的rootClass屬性中可以覆蓋該選項(xiàng)      注意:如果在key class或者record class中有root class相同的屬性,MBG就不會(huì)重新生成這些屬性了,包括:        1,屬性名相同,類型相同,有相同的getter/setter方法;     -->    <property name="rootClass" value="com._520it.mybatis.domain.BaseDomain"/>    <!-- 設(shè)置是否在getter方法中,對(duì)String類型字段調(diào)用trim()方法 -->    <property name="trimStrings" value="true"/>  </javaModelGenerator>  <!-- 生成SQL map的XML文件生成器,    注意,在Mybatis3之后,我們可以使用mapper.xml文件+Mapper接口(或者不用mapper接口),      或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的話,這個(gè)元素就必須配置    targetPackage/targetProject:同javaModelGenerator   -->  <sqlMapGenerator targetPackage="com._520it.mybatis.mapper" targetProject="src/main/resources">    <!-- 在targetPackage的基礎(chǔ)上,根據(jù)數(shù)據(jù)庫的schema再生成一層package,最終生成的類放在這個(gè)package下,默認(rèn)為false -->    <property name="enableSubPackages" value="true"/>  </sqlMapGenerator>  <!-- 對(duì)于mybatis來說,即生成Mapper接口,注意,如果沒有配置該元素,那么默認(rèn)不會(huì)生成Mapper接口     targetPackage/targetProject:同javaModelGenerator    type:選擇怎么生成mapper接口(在MyBatis3/MyBatis3Simple下):      1,ANNOTATEDMAPPER:會(huì)生成使用Mapper接口+Annotation的方式創(chuàng)建(SQL生成在annotation中),不會(huì)生成對(duì)應(yīng)的XML;      2,MIXEDMAPPER:使用混合配置,會(huì)生成Mapper接口,并適當(dāng)添加合適的Annotation,但是XML會(huì)生成在XML中;      3,XMLMAPPER:會(huì)生成Mapper接口,接口完全依賴XML;    注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER  -->  <javaClientGenerator targetPackage="com._520it.mybatis.mapper" type="ANNOTATEDMAPPER" targetProject="src/main/java">    <!-- 在targetPackage的基礎(chǔ)上,根據(jù)數(shù)據(jù)庫的schema再生成一層package,最終生成的類放在這個(gè)package下,默認(rèn)為false -->    <property name="enableSubPackages" value="true"/>    <!-- 可以為所有生成的接口添加一個(gè)父接口,但是MBG只負(fù)責(zé)生成,不負(fù)責(zé)檢查    <property name="rootInterface" value=""/>     -->  </javaClientGenerator>  <!-- 選擇一個(gè)table來生成相關(guān)文件,可以有一個(gè)或多個(gè)table,必須要有table元素    選擇的table會(huì)生成一下文件:    1,SQL map文件    2,生成一個(gè)主鍵類;    3,除了BLOB和主鍵的其他字段的類;    4,包含BLOB的類;    5,一個(gè)用戶生成動(dòng)態(tài)查詢的條件類(selectByExample, deleteByExample),可選;    6,Mapper接口(可選)    tableName(必要):要生成對(duì)象的表名;    注意:大小寫敏感問題。正常情況下,MBG會(huì)自動(dòng)的去識(shí)別數(shù)據(jù)庫標(biāo)識(shí)符的大小寫敏感度,在一般情況下,MBG會(huì)      根據(jù)設(shè)置的schema,catalog或tablename去查詢數(shù)據(jù)表,按照下面的流程:      1,如果schema,catalog或tablename中有空格,那么設(shè)置的是什么格式,就精確的使用指定的大小寫格式去查詢;      2,否則,如果數(shù)據(jù)庫的標(biāo)識(shí)符使用大寫的,那么MBG自動(dòng)把表名變成大寫再查找;      3,否則,如果數(shù)據(jù)庫的標(biāo)識(shí)符使用小寫的,那么MBG自動(dòng)把表名變成小寫再查找;      4,否則,使用指定的大小寫格式查詢;    另外的,如果在創(chuàng)建表的時(shí)候,使用的""把數(shù)據(jù)庫對(duì)象規(guī)定大小寫,就算數(shù)據(jù)庫標(biāo)識(shí)符是使用的大寫,在這種情況下也會(huì)使用給定的大小寫來創(chuàng)建表名;    這個(gè)時(shí)候,請(qǐng)?jiān)O(shè)置delimitIdentifiers="true"即可保留大小寫格式;    可選:    1,schema:數(shù)據(jù)庫的schema;    2,catalog:數(shù)據(jù)庫的catalog;    3,alias:為數(shù)據(jù)表設(shè)置的別名,如果設(shè)置了alias,那么生成的所有的SELECT SQL語句中,列名會(huì)變成:alias_actualColumnName    4,domainObjectName:生成的domain類的名字,如果不設(shè)置,直接使用表名作為domain類的名字;可以設(shè)置為somepck.domainName,那么會(huì)自動(dòng)把domainName類再放到somepck包里面;    5,enableInsert(默認(rèn)true):指定是否生成insert語句;    6,enableSelectByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵查詢對(duì)象的語句(就是getById或get);    7,enableSelectByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動(dòng)態(tài)查詢語句;    8,enableUpdateByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵修改對(duì)象的語句(即update);    9,enableDeleteByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵刪除對(duì)象的語句(即delete);    10,enableDeleteByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動(dòng)態(tài)刪除語句;    11,enableCountByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動(dòng)態(tài)查詢總條數(shù)語句(用于分頁的總條數(shù)查詢);    12,enableUpdateByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動(dòng)態(tài)修改語句(只修改對(duì)象中不為空的屬性);    13,modelType:參考context元素的defaultModelType,相當(dāng)于覆蓋;    14,delimitIdentifiers:參考tableName的解釋,注意,默認(rèn)的delimitIdentifiers是雙引號(hào),如果類似MYSQL這樣的數(shù)據(jù)庫,使用的是`(反引號(hào),那么還需要設(shè)置context的beginningDelimiter和endingDelimiter屬性)    15,delimitAllColumns:設(shè)置是否所有生成的SQL中的列名都使用標(biāo)識(shí)符引起來。默認(rèn)為false,delimitIdentifiers參考context的屬性    注意,table里面很多參數(shù)都是對(duì)javaModelGenerator,context等元素的默認(rèn)屬性的一個(gè)復(fù)寫;   -->  <table tableName="userinfo" >    <!-- 參考 javaModelGenerator 的 constructorBased屬性-->    <property name="constructorBased" value="false"/>    <!-- 默認(rèn)為false,如果設(shè)置為true,在生成的SQL中,table名字不會(huì)加上catalog或schema; -->    <property name="ignoreQualifiersAtRuntime" value="false"/>    <!-- 參考 javaModelGenerator 的 immutable 屬性 -->    <property name="immutable" value="false"/>    <!-- 指定是否只生成domain類,如果設(shè)置為true,只生成domain類,如果還配置了sqlMapGenerator,那么在mapper XML文件中,只生成resultMap元素 -->    <property name="modelOnly" value="false"/>    <!-- 參考 javaModelGenerator 的 rootClass 屬性     <property name="rootClass" value=""/>     -->    <!-- 參考javaClientGenerator 的 rootInterface 屬性    <property name="rootInterface" value=""/>    -->    <!-- 如果設(shè)置了runtimeCatalog,那么在生成的SQL中,使用該指定的catalog,而不是table元素上的catalog     <property name="runtimeCatalog" value=""/>    -->    <!-- 如果設(shè)置了runtimeSchema,那么在生成的SQL中,使用該指定的schema,而不是table元素上的schema     <property name="runtimeSchema" value=""/>    -->    <!-- 如果設(shè)置了runtimeTableName,那么在生成的SQL中,使用該指定的tablename,而不是table元素上的tablename     <property name="runtimeTableName" value=""/>    -->    <!-- 注意,該屬性只針對(duì)MyBatis3Simple有用;      如果選擇的runtime是MyBatis3Simple,那么會(huì)生成一個(gè)SelectAll方法,如果指定了selectAllOrderByClause,那么會(huì)在該SQL中添加指定的這個(gè)order條件;     -->    <property name="selectAllOrderByClause" value="age desc,username asc"/>    <!-- 如果設(shè)置為true,生成的model類會(huì)直接使用column本身的名字,而不會(huì)再使用駝峰命名方法,比如BORN_DATE,生成的屬性名字就是BORN_DATE,而不會(huì)是bornDate -->    <property name="useActualColumnNames" value="false"/>    <!-- generatedKey用于生成生成主鍵的方法,      如果設(shè)置了該元素,MBG會(huì)在生成的<insert>元素中生成一條正確的<selectKey>元素,該元素可選      column:主鍵的列名;      sqlStatement:要生成的selectKey語句,有以下可選項(xiàng):        Cloudscape:相當(dāng)于selectKey的SQL為: VALUES IDENTITY_VAL_LOCAL()        DB2    :相當(dāng)于selectKey的SQL為: VALUES IDENTITY_VAL_LOCAL()        DB2_MF  :相當(dāng)于selectKey的SQL為:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1        Derby   :相當(dāng)于selectKey的SQL為:VALUES IDENTITY_VAL_LOCAL()        HSQLDB   :相當(dāng)于selectKey的SQL為:CALL IDENTITY()        Informix :相當(dāng)于selectKey的SQL為:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1        MySql   :相當(dāng)于selectKey的SQL為:SELECT LAST_INSERT_ID()        SqlServer :相當(dāng)于selectKey的SQL為:SELECT SCOPE_IDENTITY()        SYBASE   :相當(dāng)于selectKey的SQL為:SELECT @@IDENTITY        JDBC   :相當(dāng)于在生成的insert元素上添加useGeneratedKeys="true"和keyProperty屬性    <generatedKey column="" sqlStatement=""/>     -->    <!--       該元素會(huì)在根據(jù)表中列名計(jì)算對(duì)象屬性名之前先重命名列名,非常適合用于表中的列都有公用的前綴字符串的時(shí)候,      比如列名為:CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS等;      那么就可以設(shè)置searchString為"^CUST_",并使用空白替換,那么生成的Customer對(duì)象中的屬性名稱就不是      custId,custName等,而是先被替換為ID,NAME,EMAIL,然后變成屬性:id,name,email;      注意,MBG是使用java.util.regex.Matcher.replaceAll來替換searchString和replaceString的,      如果使用了columnOverride元素,該屬性無效;    <columnRenamingRule searchString="" replaceString=""/>     -->     <!-- 用來修改表中某個(gè)列的屬性,MBG會(huì)使用修改后的列來生成domain的屬性;       column:要重新設(shè)置的列名;       注意,一個(gè)table元素中可以有多個(gè)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中,不會(huì)生成到mybatis-config.xml中的typeHandler         只會(huì)生成類似:where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler}的參數(shù)描述       <property name="jdbcType" value=""/>       -->       <!-- 參考table元素的delimitAllColumns配置,默認(rèn)為false       <property name="delimitedColumnName" value=""/>       -->     </columnOverride>     <!-- ignoreColumn設(shè)置一個(gè)MGB忽略的列,如果設(shè)置了改列,那么在生成的domain中,生成的SQL中,都不會(huì)有該列出現(xiàn)        column:指定要忽略的列的名字;       delimitedColumnName:參考table元素的delimitAllColumns配置,默認(rèn)為false       注意,一個(gè)table元素中可以有多個(gè)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配置是相對(duì)應(yīng)的。直接運(yùn)行該示例即可生成數(shù)據(jù)表對(duì)于的pojo,mapper接口和一個(gè)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配置項(xiàng)     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");         //自動(dòng)識(shí)別數(shù)據(jù)庫關(guān)鍵字,默認(rèn)false,如果設(shè)置為true,    //根據(jù)SqlReservedWords中定義的關(guān)鍵字列表;一般保留默認(rèn)值,遇到數(shù)據(jù)庫關(guān)鍵字(Java關(guān)鍵字),    //使用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);        //設(shè)置是否去除生成注釋    CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();    commentGeneratorConfiguration.addProperty("suppressAllComments","true");    //commentGeneratorConfiguration.addProperty("suppressDate","true");    context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);      //設(shè)置連接數(shù)據(jù)庫    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可自動(dòng)轉(zhuǎn)化以下類型(Long, Integer, Short, etc.)    javaTypeResolverConfiguration.addProperty("forceBigDecimals","false");    context.setJavaTypeResolverConfiguration(javaTypeResolverConfiguration);        //生成實(shí)體類的地址    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;@Servicepublic 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);  }    /**   * 根據(jù)ID更新用戶信息   * @param userInfo   * @return   */  public Integer updateUser(UserInfo userInfo) {    return userInfoMapper.updateByPrimaryKey(userInfo);  }    /**   * 根據(jù)ID刪除用戶   * @param id   * @return   */  public Integer deleteUserById(Integer id) {    return userInfoMapper.deleteByPrimaryKey(id);  }}

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到JAVA教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 亚洲资源在线 | 一本色道精品久久一区二区三区 | 爱草成年 | 欧美一级毛片免费观看 | 成人精品一区二区 | 中文字幕亚洲情99在线 | 亚洲国产精品久久久 | 欧美日韩在线影院 | 一级做a爱片久久毛片a高清 | a网站在线| 日韩精品久久久久久 | 久久精品亚洲欧美日韩精品中文字幕 | 色播亚洲 | 欧美城网站地址 | www国产免费 | 一级做a爱性色毛片免费1 | 黄色片网站在线看 | 日韩激情在线视频 | 欧美日韩夜夜 | 亚洲午夜精品视频 | 欧美国产日韩在线观看成人 | 91精品国产综合久久男男 | 特级毛片全部免费播放器 | 日本高清一级片 | 国产又粗又爽又深的免费视频 | 精品国产一区二区三区四区在线 | 免费看欧美黑人毛片 | 久久综合久久美利坚合众国 | 九草在线视频 | 97超碰资源站| 精品国产一区二区三区久久久蜜月 | 午夜视频在线 | 永久免费在线观看av | 成人福利视频在线观看 | 92看片淫黄大片欧美看国产片 | 国产精品成人一区二区三区吃奶 | 免费在线观看国产精品 | 亚洲一级毛片 | 一级片九九 | 久久久久国产一区二区三区不卡 | 国产资源在线免费观看 |