使用MyBatis-Generator自动生成映射文件
生成的方式一共有三种
1、使用cmd命令方式生成。
首先在generator.xml中指定数据库驱动包位置,然后在mybatis-generator-core-1.3.1包下创建一个src文件夹(否则生成的文件没地方放)
生产的Mapper.xml文件与domain类放在一个报下面(否则无法映射)
E:/>java -jar E:/mybatis-generator-core-1.3.1/lib/mybatis-generator-core-1.3.1.jar -configfile E:/mybatis-generator-core-1.3.1/generator.xml -overwritegenerator.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> <!-- 数据库驱动位置 --> <classPathEntry location="E:/mybatis-generator-core-1.3.1/MySQL-connector-java-5.0.8-bin.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <PRoperty name="suppressAllComments" value="true" /> </commentGenerator> <!-- 数据库的url、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/dbo" userId="root" passWord="123456"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="com.paywing.domain" targetProject="E:/mybatis-generator-core-1.3.1/src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的映射文件包名和位置 --> <sqlMapGenerator targetPackage="com.paywing.mapping" targetProject="E:/mybatis-generator-core-1.3.1/src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.paywing.dao" targetProject="E:/mybatis-generator-core-1.3.1/src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 生成那些表 tableName表名,domainObjectName应于数据库表的javaBean类名--> <table tableName="tb_bookinfo" domainObjectName="TB_BookInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/> <table tableName="tb_booktype" domainObjectName="TB_Booktype" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> </context></generatorConfiguration>2、使用maven方式生成(这种方式在各个工具下都能使用,推荐使用这种方式)。
generator.properties
#工程src路径 这里如果是maven启动的话去掉mybatis/ project=mybatis/src/main/java #工程存放mapper.xml路径 这里如果是maven启动的话去掉mybatis/ resource=mybatis/src/main/resourcespackage_domain=com.practice.mybatis.entitypackage_mapper=mappers.testpackage_dao=com.practice.mybatis.daopackage_service=com.practice.mybatis.service #/u6307/u5B9A/u6570/u636E/u8FDE/u63A5/u9A71/u52A8jar/u5730/u5740 classPath=D:/maven_lib/mysql/mysql-connector-java/5.1.30/mysql-connector-java-5.1.30.jar jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8jdbc.user=rootjdbc.password=123456generatorConfig.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="generator.properties"/> <!-- 数据库驱动位置 --> <classPathEntry location="${classPath}" /> <!-- 一个数据库一个context, targetRuntime:此属性用于指定生成的代码的运行时环境 ,MyBatis3:*这是默认值*,MyBatis3Simple不生成Example查询(避免后面一个一个表设置) defaultModelType:如何生成实体类,flat表示为每一张表生成一个实体类,推荐使用--> <context id="mysqlTables" targetRuntime="com.practice.mybatis.TkMyBatis3Impl" defaultModelType="flat"> <!-- 注释 type表示自定义注释--> <commentGenerator type="com.practice.mybatis.MyCommentGenerator"> <!-- 生成文件的编码 (eclipse插件的时候这里并没有什么卵用,需要在eclipse根目录的eclipse.ini最后添加 -Dfile.encoding=UTF-8 )--> <property name="javaFileEncoding" value="UTF-8"/> <!-- 是否取消注释 --> <property name="suppressAllComments" value="false" /> <property name="addRemarkComments" value="true"/> <!-- 是否生成注释代时间戳 --> <property name="suppressDate" value="true" /> <!-- 当表名或者字段名为SQL关键字的时候,可以设置该属性为true,MBG会自动给表名或字段名添加**分隔符** --> <property name="autoDelimitKeywords" value="true"></property> <!-- 由于beginningDelimiter和endingDelimiter的默认值为双引号("),在Mysql中不能这么写,所以还要将这两个默认值改为**反单引号(`)** --> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> </commentGenerator> <!-- 数据库的url、用户名、密码 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.user}" password="${jdbc.password}"> </jdbcConnection> <!-- 类型转换 --> <javaTypeResolver > <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="${package_domain}" targetProject="${project}"> <!-- 是否在当前路径下新加一层schema,eg:fase路径com.goshop.domain", true:com.goshop.domain".[schemaName] --> <property name="enableSubPackages" value="false" /> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的映射文件包名和位置 --> <sqlMapGenerator targetPackage="${package_mapper}" targetProject="${resource}"> <!-- 是否在当前路径下新加一层schema,eg:fase路径com.goshop.domain", true:com.goshop.domain".[schemaName] --> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 type 1、ANNOTATEDMAPPER注解形式 2、XMLMAPPER xml配置文件形式--> <javaClientGenerator type="XMLMAPPER" targetPackage="${package_dao}" targetProject="${project}"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 生成那些表 tableName表名 mapperName 生成dao的名称,domainObjectName应于数据库表的javaBean类名,enable*ByExample是否生成 example类 --> <!-- <table tableName="sys_user" domainObjectName="SysUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/> --> <!-- 忽略列,不生成bean 字段 <ignoreColumn column="FRED" />--> <!-- 指定列的java数据类型 <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />--> <table tableName="%" mapperName="{0}DAO"> <columnOverride column="remarks" jdbcType="VARCHAR" /> </table></context></generatorConfiguration>注意:这里由于需要自定义中文注释,因此需要修改源码,这里附上修改后的代码。
MyCommentGenerator.java
这个文件是关于注释的部分,只需要实现CommentGenerator接口就可以。
/** * Copyright 2006-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.practice.mybatis;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import java.util.Properties;import org.mybatis.generator.api.CommentGenerator;import org.mybatis.generator.api.IntrospectedColumn;import org.mybatis.generator.api.IntrospectedTable;import org.mybatis.generator.api.dom.java.CompilationUnit;import org.mybatis.generator.api.dom.java.Field;import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;import org.mybatis.generator.api.dom.java.InnerClass;import org.mybatis.generator.api.dom.java.InnerEnum;import org.mybatis.generator.api.dom.java.JavaElement;import org.mybatis.generator.api.dom.java.Method;import org.mybatis.generator.api.dom.java.Parameter;import org.mybatis.generator.api.dom.java.TopLevelClass;import org.mybatis.generator.api.dom.xml.TextElement;import org.mybatis.generator.api.dom.xml.XmlElement;import org.mybatis.generator.config.MergeConstants;import org.mybatis.generator.config.PropertyRegistry;import org.mybatis.generator.internal.util.StringUtility;/** * 修改Mybatis Generator 生成的所有注释的文档 * * @author wl */public class MyCommentGenerator implements CommentGenerator { /** The properties. */ private Properties properties; /** The suppress date. */ private boolean suppressDate; /** The suppress all comments. */ private boolean suppressAllComments; /** The addition of table remark's comments. * If suppressAllComments is true, this option is ignored*/ private boolean addRemarkComments; private SimpleDateFormat dateFormat; /** * Instantiates a new default comment generator. */ public MyCommentGenerator() { super(); properties = new Properties(); suppressDate = false; suppressAllComments = false; addRemarkComments = false; } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addJavaFileComment(org.mybatis.generator.api.dom.java.CompilationUnit) */ public void addJavaFileComment(final CompilationUnit compilationUnit) { // add no file level comments by default } /** * Adds a suitable comment to warn users that the element was generated, and when it was generated. * * @param xmlElement * the xml element */ public void addComment(final XmlElement xmlElement) { if (suppressAllComments) { return; } xmlElement.addElement(new TextElement("<!--")); //$NON-NLS-1$ final StringBuilder sb = new StringBuilder();// sb.append(" WARNING - "); //$NON-NLS-1$ sb.append(MergeConstants.NEW_ELEMENT_TAG); xmlElement.addElement(new TextElement(sb.toString()));// xmlElement// .addElement(new TextElement(// " This element is automatically generated by MyBatis Generator, do not modify.")); //$NON-NLS-1$//// final String s = getDateString();// if (s != null) {// sb.setLength(0);// sb.append(" This element was generated on "); //$NON-NLS-1$// sb.append(s);// sb.append('.');// xmlElement.addElement(new TextElement(sb.toString()));// } xmlElement.addElement(new TextElement("-->")); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addRootComment(org.mybatis.generator.api.dom.xml.XmlElement) */ public void addRootComment(final XmlElement rootElement) { // add no document level comments by default } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addConfigurationProperties(java.util.Properties) */ public void addConfigurationProperties(final Properties properties) { this.properties.putAll(properties); suppressDate = isTrue(properties .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE)); suppressAllComments = isTrue(properties .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS)); addRemarkComments = isTrue(properties .getProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS)); final String dateFormatString = properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_DATE_FORMAT); if (StringUtility.stringHasValue(dateFormatString)) { dateFormat = new SimpleDateFormat(dateFormatString); } } public static boolean isTrue(String s) { return "true".equalsIgnoreCase(s); //$NON-NLS-1$ } /** * This method adds the custom javadoc tag for. You may do nothing if you do not wish to include the Javadoc tag - * however, if you do not include the Javadoc tag then the Java merge capability of the eclipse plugin will break. * * @param javaElement * the java element * @param markAsDoNotDelete * the mark as do not delete */ protected void addJavadocTag(final JavaElement javaElement, final boolean markAsDoNotDelete) { javaElement.addJavaDocLine(" *"); //$NON-NLS-1$ final StringBuilder sb = new StringBuilder(); sb.append(" * "); //$NON-NLS-1$ sb.append(MergeConstants.NEW_ELEMENT_TAG); if (markAsDoNotDelete) { sb.append(" do_not_delete_during_merge"); //$NON-NLS-1$ } final String s = getDateString(); if (s != null) { sb.append(' '); sb.append(s); } javaElement.addJavaDocLine(sb.toString()); } /** * This method returns a formated date string to include in the Javadoc tag * and XML comments. You may return null if you do not want the date in * these documentation elements. * * @return a string representing the current timestamp, or null */ protected String getDateString() { if (suppressDate) { return null; } else if (dateFormat != null) { return dateFormat.format(new Date()); } else { return new Date().toString(); } } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addClassComment(org.mybatis.generator.api.dom.java.InnerClass, org.mybatis.generator.api.IntrospectedTable) */ public void addClassComment(final InnerClass innerClass, final IntrospectedTable introspectedTable) { if (suppressAllComments) { return; } final StringBuilder sb = new StringBuilder(); innerClass.addJavaDocLine("/**"); //$NON-NLS-1$ innerClass .addJavaDocLine(" * This class was generated by MyBatis Generator."); //$NON-NLS-1$ sb.append(" * This class corresponds to the database table "); //$NON-NLS-1$ sb.append(introspectedTable.getFullyQualifiedTable()); innerClass.addJavaDocLine(sb.toString()); addJavadocTag(innerClass, false); innerClass.addJavaDocLine(" */"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addTopLevelClassComment(org.mybatis.generator.api.dom.java.TopLevelClass, org.mybatis.generator.api.IntrospectedTable) */ public void addModelClassComment(final TopLevelClass topLevelClass, final IntrospectedTable introspectedTable) { if (suppressAllComments || !addRemarkComments) { return; } final StringBuilder sb = new StringBuilder(); topLevelClass.addJavaDocLine("/**"); //$NON-NLS-1$ final String remarks = introspectedTable.getRemarks(); if (addRemarkComments && StringUtility.stringHasValue(remarks)) { topLevelClass.addJavaDocLine(" * Database Table Remarks:"); final String[] remarkLines = remarks.split(System.getProperty("line.separator")); //$NON-NLS-1$ for (String remarkLine : remarkLines) { topLevelClass.addJavaDocLine(" * " + remarkLine); //$NON-NLS-1$ } }// topLevelClass.addJavaDocLine(" *"); //$NON-NLS-1$// topLevelClass// .addJavaDocLine(" * This class was generated by MyBatis Generator."); //$NON-NLS-1$// sb.append(" * This class corresponds to the database table "); //$NON-NLS-1$ sb.append(" * 对应于数据库表 "); //$NON-NLS-1$ sb.append(introspectedTable.getFullyQualifiedTable()); topLevelClass.addJavaDocLine(sb.toString()); addJavadocTag(topLevelClass, true); topLevelClass.addJavaDocLine(" */"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addEnumComment(org.mybatis.generator.api.dom.java.InnerEnum, org.mybatis.generator.api.IntrospectedTable) */ public void addEnumComment(final InnerEnum innerEnum, final IntrospectedTable introspectedTable) { if (suppressAllComments) { return; }// StringBuilder sb = new StringBuilder(); innerEnum.addJavaDocLine("/**"); //$NON-NLS-1$// innerEnum// .addJavaDocLine(" * This enum was generated by MyBatis Generator."); //$NON-NLS-1$//// sb.append(" * This enum corresponds to the database table "); //$NON-NLS-1$// sb.append(introspectedTable.getFullyQualifiedTable());// innerEnum.addJavaDocLine(sb.toString()); addJavadocTag(innerEnum, false); innerEnum.addJavaDocLine(" */"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addFieldComment(org.mybatis.generator.api.dom.java.Field, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn) */ public void addFieldComment(final Field field, final IntrospectedTable introspectedTable, final IntrospectedColumn introspectedColumn) { if (suppressAllComments) { return; } field.addJavaDocLine("/**"); //$NON-NLS-1$ String remarks = introspectedColumn.getRemarks(); if (addRemarkComments && StringUtility.stringHasValue(remarks)) { field.addJavaDocLine(" * Database Column Remarks:"); final String[] remarkLines = remarks.split(System.getProperty("line.separator")); //$NON-NLS-1$ for (String remarkLine : remarkLines) { field.addJavaDocLine(" * " + remarkLine); //$NON-NLS-1$ } }// field.addJavaDocLine(" *"); //$NON-NLS-1$ StringBuilder sb = new StringBuilder(); sb.append(" * "+introspectedTable.getFullyQualifiedTable()); sb.append('.'); sb.append(introspectedColumn.getActualColumnName()); sb.append(introspectedColumn.getRemarks()==null ? " " : " "+introspectedColumn.getRemarks()); field.addJavaDocLine(sb.toString()); addJavadocTag(field, false); field.addJavaDocLine(" */"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addFieldComment(org.mybatis.generator.api.dom.java.Field, org.mybatis.generator.api.IntrospectedTable) */ public void addFieldComment(final Field field, final IntrospectedTable introspectedTable) { if (suppressAllComments) { return; } final StringBuilder sb = new StringBuilder(); field.addJavaDocLine("/**"); //$NON-NLS-1$ field .addJavaDocLine(" * This field was generated by MyBatis Generator."); //$NON-NLS-1$ sb.append(" * This field corresponds to the database table "); //$NON-NLS-1$ sb.append(introspectedTable.getFullyQualifiedTable()); field.addJavaDocLine(sb.toString()); addJavadocTag(field, false); field.addJavaDocLine(" */"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addGeneralMethodComment(org.mybatis.generator.api.dom.java.Method, org.mybatis.generator.api.IntrospectedTable) */ public void addGeneralMethodComment(final Method method, final IntrospectedTable introspectedTable) { if (suppressAllComments) { return; } StringBuilder sb = new StringBuilder(); method.addJavaDocLine("/**"); //$NON-NLS-1$// method// .addJavaDocLine(" * This method was generated by MyBatis Generator."); //$NON-NLS-1$//// sb.append(" * This method corresponds to the database table "); //$NON-NLS-1$// sb.append(introspectedTable.getFullyQualifiedTable()); List<Parameter> parameters = method.getParameters(); for (Parameter parameter : parameters) { sb.append(" *@param "); sb.append(parameter.getName()); sb.append("."); method.addJavaDocLine(sb.toString()); sb.delete(0, sb.length()); } method.addJavaDocLine(method.getReturnType().getShortName()==null ? "" :" *@return "+method.getReturnType().getShortName()+"."); addJavadocTag(method, false); method.addJavaDocLine(" */"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addGetterComment(org.mybatis.generator.api.dom.java.Method, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn) */ public void addGetterComment(final Method method, final IntrospectedTable introspectedTable, final IntrospectedColumn introspectedColumn) { if (suppressAllComments) { return; } StringBuilder sb = new StringBuilder(); method.addJavaDocLine("/**"); //$NON-NLS-1$// method// .addJavaDocLine(" * This method was generated by MyBatis Generator."); //$NON-NLS-1$//// sb.append(" * This method returns the value of the database column "); //$NON-NLS-1$// sb.append(introspectedTable.getFullyQualifiedTable());// sb.append('.');// sb.append(introspectedColumn.getActualColumnName());// method.addJavaDocLine(sb.toString());//// method.addJavaDocLine(" *"); //$NON-NLS-1$//// sb.setLength(0);// sb.append(" * @return the value of "); //$NON-NLS-1$// sb.append(introspectedTable.getFullyQualifiedTable());// sb.append('.');// sb.append(introspectedColumn.getActualColumnName()); sb.append(" * @return "+( introspectedColumn.getActualColumnName()==null ? "":introspectedColumn.getActualColumnName())); sb.append(" ."); method.addJavaDocLine(sb.toString()); addJavadocTag(method, false); method.addJavaDocLine(" */"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addSetterComment(org.mybatis.generator.api.dom.java.Method, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn) */ public void addSetterComment(final Method method, final IntrospectedTable introspectedTable, final IntrospectedColumn introspectedColumn) { if (suppressAllComments) { return; } StringBuilder sb = new StringBuilder(); method.addJavaDocLine("/**"); //$NON-NLS-1$// method// .addJavaDocLine(" * This method was generated by MyBatis Generator."); //$NON-NLS-1$//// sb.append(" * This method sets the value of the database column "); //$NON-NLS-1$// sb.append(introspectedTable.getFullyQualifiedTable());// sb.append('.');// sb.append(introspectedColumn.getActualColumnName());// method.addJavaDocLine(sb.toString());//// method.addJavaDocLine(" *"); //$NON-NLS-1$// Parameter parm = method.getParameters().get(0); sb.setLength(0); sb.append(" * @param "); //$NON-NLS-1$ sb.append(parm.getName()); sb.append((introspectedColumn.getRemarks()==null ? " " : " "+introspectedColumn.getRemarks())); sb.append(".");// sb.append(" the value for "); //$NON-NLS-1$// sb.append(introspectedTable.getFullyQualifiedTable());// sb.append('.');// sb.append(introspectedColumn.getActualColumnName()); method.addJavaDocLine(sb.toString()); addJavadocTag(method, false); method.addJavaDocLine(" */"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.mybatis.generator.api.CommentGenerator#addClassComment(org.mybatis.generator.api.dom.java.InnerClass, org.mybatis.generator.api.IntrospectedTable, boolean) */ public void addClassComment(final InnerClass innerClass, final IntrospectedTable introspectedTable, final boolean markAsDoNotDelete) { if (suppressAllComments) { return; } final StringBuilder sb = new StringBuilder(); innerClass.addJavaDocLine("/**"); //$NON-NLS-1$ innerClass .addJavaDocLine(" * This class was generated by MyBatis Generator."); //$NON-NLS-1$ sb.append(" * This class corresponds to the database table "); //$NON-NLS-1$ sb.append(introspectedTable.getFullyQualifiedTable()); innerClass.addJavaDocLine(sb.toString()); addJavadocTag(innerClass, markAsDoNotDelete); innerClass.addJavaDocLine(" */"); //$NON-NLS-1$ }} 1.3.4 版本以后,MBG 在元素上提供了一个mapperName
的属性,可以设置生成的 Mapper 名字。
但是因为 tableName 属性支持通配符 %,在这种情况下就不能使用mapperName属性设置了。为了解决这种情况,提供了一个插件可以用于通配符情况下的配置。
package com.practice.mybatis;import java.text.MessageFormat;import org.mybatis.generator.codegen.mybatis3.IntrospectedTableMyBatis3SimpleImpl;/** * @author Win7 *生成DAO后缀 */public class TkMyBatis3Impl extends IntrospectedTableMyBatis3SimpleImpl { @Override protected String calculateMyBatis3XmlMapperFileName() { final StringBuilder sb = new StringBuilder(); if (stringHasValue(tableConfiguration.getMapperName())) { String mapperName = tableConfiguration.getMapperName(); final int ind = mapperName.lastIndexOf('.'); if (ind != -1) { mapperName = mapperName.substring(ind + 1); } //支持mapperName = "{0}Dao" 等用法 sb.append(MessageFormat.format(mapperName, fullyQualifiedTable.getDomainObjectName())); sb.append(".xml"); //$NON-NLS-1$ } else { sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("Mapper.xml"); //$NON-NLS-1$ } return sb.toString(); } public static boolean stringHasValue(final String s) { return s != null && s.length() > 0; } @Override protected void calculateJavaClientAttributes() { if (context.getJavaClientGeneratorConfiguration() == null) { return; } final StringBuilder sb = new StringBuilder(); sb.append(calculateJavaClientImplementationPackage()); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("DAOImpl"); //$NON-NLS-1$ setDAOImplementationType(sb.toString()); sb.setLength(0); sb.append(calculateJavaClientInterfacePackage()); sb.append('.'); sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("DAO"); //$NON-NLS-1$ setDAOInterfaceType(sb.toString()); sb.setLength(0); sb.append(calculateJavaClientInterfacePackage()); sb.append('.'); if (stringHasValue(tableConfiguration.getMapperName())) { //支持mapperName = "{0}Dao" 等用法 sb.append(MessageFormat.format(tableConfiguration.getMapperName(), fullyQualifiedTable.getDomainObjectName())); } else { sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("Mapper"); //$NON-NLS-1$ } setMyBatis3JavaMapperType(sb.toString()); sb.setLength(0); sb.append(calculateJavaClientInterfacePackage()); sb.append('.'); if (stringHasValue(tableConfiguration.getSqlProviderName())) { //支持mapperName = "{0}SqlProvider" 等用法 sb.append(MessageFormat.format(tableConfiguration.getSqlProviderName(), fullyQualifiedTable.getDomainObjectName())); } else { sb.append(fullyQualifiedTable.getDomainObjectName()); sb.append("SqlProvider"); //$NON-NLS-1$ } setMyBatis3SqlProviderType(sb.toString()); }}以上是所有的配置,下面设置maven启动
IDEA下(wl.jar是需要添加中文注释所修改的源码后打的jar)
pom.xml
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <dependency> <groupId>mygenerator</groupId> <artifactId>com.mybatis.generator.wl</artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/com.mybatis.generator.wl.jar</systemPath> </dependency> </dependencies> <configuration> <!--配置文件的路径--> <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile> <!--允许移动生成的文件--> <verbose>true</verbose> <!--允许覆盖生成的文件--> <overwrite>true</overwrite> </configuration> </plugin>maven配置
Command line:
mybatis-generator:generateeclipse下
pom.xml配置同上
Goals
mybatis-generator:generate注意:maven方式启动的话,上面geterator.properties里的project与resource 需要去掉项目名称。
generatorConfig.xml里面targetRuntime与自定义注释的java文件配置的是修改完源码导入到项目中jar的路径。
3、如果开发工具为eclipse,可以安装Generator的插件,然后生成generatorConfig.xml进行修改配置。
最后通过右键就可以运行。
新闻热点
疑难解答