使用MyBatis-Generator如何自动生成映射文件
MyBatis-Generator自动生成映射文件
生成的方式一共有三种
1、使用cmd命令方式生成
首先在generator.xml中指定数据库驱动包位置,然后在mybatis-generator-core-1.3.1包下创建一个class="lazy" data-src文件夹(否则生成的文件没地方放)
生产的Mapper.xml文件与domain类放在一个报下面(否则无法映射)
E:\>java -jar E:\mybatis-generator-core-1.3.1\lib\mybatis-generator-core-1.3.1.j
ar -configfile E:\mybatis-generator-core-1.3.1\generator.xml -overwrite
generator.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\class="lazy" data-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\class="lazy" data-src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.paywing.dao" targetProject="E:\mybatis-generator-core-1.3.1\class="lazy" data-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
#工程class="lazy" data-src路径 这里如果是maven启动的话去掉mybatis/
project=mybatis/class="lazy" data-src/main/java
#工程存放mapper.xml路径 这里如果是maven启动的话去掉mybatis/
resource=mybatis/class="lazy" data-src/main/resources
package_domain=com.practice.mybatis.entity
package_mapper=mappers.test
package_dao=com.practice.mybatis.dao
package_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.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=123456
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="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接口就可以。
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;
public class MyCommentGenerator implements CommentGenerator {
private Properties properties;
private boolean suppressDate;
private boolean suppressAllComments;
private boolean addRemarkComments;
private SimpleDateFormat dateFormat;
public MyCommentGenerator() {
super();
properties = new Properties();
suppressDate = false;
suppressAllComments = false;
addRemarkComments = false;
}
public void addJavaFileComment(final CompilationUnit compilationUnit) {
// add no file level comments by default
}
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$
}
public void addRootComment(final XmlElement rootElement) {
// add no document level comments by default
}
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$
}
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());
}
protected String getDateString() {
if (suppressDate) {
return null;
} else if (dateFormat != null) {
return dateFormat.format(new Date());
} else {
return new Date().toString();
}
}
public void addClassComment(final InnerClass innerClass,
final IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
final StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine(""); //$NON-NLS-1$
}
public void addModelClassComment(final TopLevelClass topLevelClass,
final IntrospectedTable introspectedTable) {
if (suppressAllComments || !addRemarkComments) {
return;
}
final StringBuilder sb = new StringBuilder();
topLevelClass.addJavaDocLine(""); //$NON-NLS-1$
}
public void addEnumComment(final InnerEnum innerEnum,
final IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
// StringBuilder sb = new StringBuilder();
innerEnum.addJavaDocLine(""); //$NON-NLS-1$
}
public void addFieldComment(final Field field,
final IntrospectedTable introspectedTable,
final IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
field.addJavaDocLine(""); //$NON-NLS-1$
}
public void addFieldComment(final Field field, final IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
final StringBuilder sb = new StringBuilder();
field.addJavaDocLine(""); //$NON-NLS-1$
}
public void addGeneralMethodComment(final Method method,
final IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
method.addJavaDocLine(""); //$NON-NLS-1$
}
public void addGetterComment(final Method method,
final IntrospectedTable introspectedTable,
final IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
method.addJavaDocLine(""); //$NON-NLS-1$
}
public void addSetterComment(final Method method,
final IntrospectedTable introspectedTable,
final IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
method.addJavaDocLine(""); //$NON-NLS-1$
}
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$
}
}
1.3.4 版本以后,MBG 在元素上提供了一个mapperName 的属性,可以设置生成的 Mapper 名字。
但是因为 tableName 属性支持通配符 %,在这种情况下就不能使用mapperName属性设置了。为了解决这种情况,提供了一个插件可以用于通配符情况下的配置。
package com.practice.mybatis;
import java.text.MessageFormat;
import org.mybatis.generator.codegen.mybatis3.IntrospectedTableMyBatis3SimpleImpl;
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}\class="lazy" data-src\main\webapp\WEB-INF\lib\com.mybatis.generator.wl.jar</systemPath>
</dependency>
</dependencies>
<configuration>
<!--配置文件的路径-->
<configurationFile>${basedir}/class="lazy" data-src/main/resources/generatorConfig.xml</configurationFile>
<!--允许移动生成的文件-->
<verbose>true</verbose>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
</configuration>
</plugin>
maven配置
Command line:
mybatis-generator:generate
eclipse下
pom.xml配置同上
Goals
mybatis-generator:generate
注意:maven方式启动的话,上面geterator.properties里的project与resource 需要去掉项目名称。
generatorConfig.xml里面targetRuntime与自定义注释的java文件配置的是修改完源码导入到项目中jar的路径。
3、如果开发工具为eclipse
可以安装Generator的插件,然后生成generatorConfig.xml进行修改配置。
最后通过右键就可以运行。
自动生成MyBatis映射文件工具
问题
总是自己写crud的操作太烦躁了,还不如直接自动生成一下curd的操作了,自己写查询的操作,接下来就提供给一个很好用的快捷生成mapper和mapper映射文件的工具类,将这个工具xml文件直接放到resource文件夹下就可以了!!
<build>
<finalName>com.jimi.house</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArguments>
<verbose/>
<bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</bootclasspath>
</compilerArguments>
<!--<encoding>UTF-8</encoding>-->
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
<?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="D:/apache-maven-3.5.0/repo/mysql/mysql-connector-java/5.1.35/mysql-connector-java-5.1.35.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/identity" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.chaimao.newparent.entity" targetProject="class="lazy" data-src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="class="lazy" data-src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.chaimao.newparent.mapper" targetProject="class="lazy" data-src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="identity_record" domainObjectName="IdentityRecord" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341