Mybatis Generator(MBG)是Mybatis的一個代碼生成工具。MBG解決了對數據庫操做有最大影響的一些CRUD操做,很大程度上提高開發效率。若是須要聯合查詢仍然須要手寫sql。相信不少人都據說過微服務,各個微服務之間是鬆耦合的。每一個微服務僅關注於完成一件任務並很好地完成該任務。在一個微服務的開發過程當中極可能只關注對單表的操做。因此MBG在開發過程當中能夠快速的生成代碼提高開發效率。java
本文將說到在springboot的項目中如何去配置(XML形式和Java配置類形式)和使用MBG以及MBG生成代碼的兩種方式(XML形式和註解形式),在springboot中更推薦去使用註解的形式。mysql
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency>
2.XML配置spring
配置示例:在新建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>
配置詳解sql
<?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類。api
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); } }