Mybatis使用generator自动生成映射配置文件信息
- 格式:docx
- 大小:179.34 KB
- 文档页数:4
idea mybatis generate使用idea是一款非常流行的Java集成开发环境,可以帮助开发者更高效地进行软件开发。
而MyBatis是一个优秀的持久层框架,可以帮助开发者更方便地操作数据库。
那么,在idea中如何使用MyBatis Generator来生成代码呢?首先,我们需要在idea中安装MyBatis Generator插件。
在idea的插件市场中搜索MyBatis Generator,并进行安装。
安装完成后,重启idea以使插件生效。
接下来,我们需要配置MyBatis Generator插件。
在idea中找到插件的配置选项,输入数据库连接信息,包括数据库地址、用户名、密码等。
确保配置信息正确无误。
然后,我们需要在idea中创建一个MyBatis Generator配置文件。
在项目中新建一个xml文件,命名为generatorConfig.xml。
在配置文件中指定要生成的表格、实体类、Mapper接口等信息。
可以根据需要进行自定义配置,比如指定生成代码的路径、生成的代码风格等。
接着,我们可以通过右键点击配置文件,选择Run As MyBatis Generator来执行代码生成任务。
插件会自动读取配置文件,并生成相应的代码文件。
在生成过程中,我们可以在idea的控制台中查看详细的生成过程和结果。
最后,我们可以在项目中看到生成的代码文件。
包括实体类、Mapper接口、Mapper映射文件等。
这些代码文件可以帮助我们更快速地完成数据库操作,提高开发效率。
总的来说,使用MyBatis Generator插件可以帮助开发者快速生成数据库相关的代码文件,减少重复劳动,提高开发效率。
通过在idea中配置和运行MyBatisGenerator插件,我们可以轻松地生成所需的代码文件,让开发工作变得更加便捷。
希望以上内容对想要在idea中使用MyBatis Generator的开发者有所帮助。
mybatis generator 插件运行原理
生成器是MybatisGenerator的核心组件之一,它定义了生成映
射文件、Java Bean 类和 DAO 接口的规则和逻辑。
Mybatis Generator 中提供了多种不同类型的生成器,包括基于数据库表结构的生成器、基于 XML 配置文件的生成器等。
生成器上下文是 Mybatis Generator 的另一个核心组件,它负
责将生成器生成的代码写入到指定的文件中。
生成器上下文根据生成器的类型和配置文件中的配置信息,确定生成的代码需要写入到哪些文件中,以及如何组织生成的代码。
Mybatis Generator 插件的运行流程大致为:
1. 读取配置文件:Mybatis Generator 插件通过读取配置文件(即 Mybatis Generator 配置文件)来确定需要生成的代码类型和
对应的生成器类型。
2. 创建生成器:根据配置文件中指定的生成器类型和参数,创
建对应的生成器实例。
3. 创建生成器上下文:根据配置文件中指定的生成器上下文类
型和参数,创建对应的生成器上下文实例。
4. 执行生成器:将生成器实例和生成器上下文实例传入
Mybatis Generator 中的核心执行类,执行生成器的 generate 方法,生成对应的代码文件。
5. 输出结果:将生成的代码文件按照生成器上下文的要求写入
到指定的文件中。
总的来说,Mybatis Generator 插件的运行原理主要是通过生成器和生成器上下文实现的。
在生成器和生成器上下文的配合下,Mybatis Generator 插件可以快速、准确地生成对应的代码文件。
使用Mybat is Generat or自动生成Mybati s相关代码本文将简要介绍怎样利用My batisGenerat or自动生成Mybati s的相关代码:一、构建一个环境:1. 首先创建一个表:Sql代码1.CREATETABLE pet (name VARCHAR(20), owner VARCHAR(20), speciesVARCHAR(20), sex CHAR(1), birth DATE, death DATE);2. 然后注入数据Sql代码1.insertinto pet values('Fluffy', 'Harold', 'cat', 'f', '1993-02-04', null);2.insertinto pet values('Claws', 'Gwen', 'cat', 'm', '1994-03-17', null);3.insertinto pet values('Buffy', 'Harold', 'dog', 'f', '1989-05-13', null);4.insertinto pet values('Fang', 'Benny', 'dog', 'm', '1990-08-27', null);5.insertinto pet values('Bowser', 'Diane', 'dog', 'm', '1979-08-31', '1995-07-29');6.insertinto pet values('Chirpy', 'Gwen', 'bird', 'f', '1998-09-11', null);7.insertinto pet values('Whistle r', 'Gwen', 'bird', null, '1997-12-09', null);8.insertinto pet values('Slim', 'Benny', 'snake', 'm', '1996-04-29', null);注:这里的sql例子来自/doc/refman/5.5/en/creatin g-tables.html3. 在 Mybatis主页 http://code.google.com/p/mybatis/ 上下载 Mybatis mybatis-generat or-core [本文使用的是1.3.0 版本]。
mybatis-generator数据库注释实体类⽣成以及generatorConfig⽂件配置项⽬⾥新建表时model,mapper以及mapper.xml基本都是⽤Mybatis Generator(以下简称为MBG)⾃动⽣成的,但是MBG⾃动⽣成的model的注释实在有点⾮⼈类,⾄少中国⼈是完全接受不了的,在配置中禁⽤掉注释吧,倒是简单了,可是⽣成的model类光秃秃的,啥都没有,字段⽅法没有注释,使⽤很不⽅便,别⼈看也不知道这个字段是啥含义,到最后还是要⾃⼰添加,⼀张表多点⼏⼗个字段,特么添加累死了,不能这么⼲,得想法⼦,百度了⼀下⽹上,基本有两种⽅法,第⼀种,就是直接修改MGB的源代码,第⼆种就是⾃⼰写⼀个类实现CommentGenerator接⼝,先说⾃⼰写⼀个新类实现CommentGenerator接⼝的⽅法来使⾃动⽣成的model类含有中⽂注释吧.⼀:⾸先你得有⼀个maven项⽬,这个我就不多提⼆:通过mybatis generator实现⾃动⽣产model,mapper以及mapper.xml,具体参考 Intellij IDEA 14中使⽤MyBatis-generator ⾃动⽣成MyBatis代码三:通过查看你会发现,注解类是在mybatis-generator-core jar包中 org.mybatis.generator.internal包下的DefaultCommentGenerator类。
那么这⾥有两种⽅法,⼀种是重写DefaultCommentGenerator类,另外⼀种中修改jar包中的源码,但很明显第⼀种⽅法⽐较简单,这⾥也只介绍第⼀种⽅法的写法。
3.1在源代码中新建⼀个类MyCommentGenerator,实现CommentGenerator接⼝,类的代码如下:package org.mybatis.generator;/*** Created by 草帽boy on 2017/2/16.* mybatis generator ⾃定义comment⽣成器.* 基于MBG 1.3.2.* @author ZhangAY 2016-02-19*/import java.text.SimpleDateFormat;import java.util.Date;import java.util.Properties;import mentGenerator;import org.mybatis.generator.api.IntrospectedColumn;import org.mybatis.generator.api.IntrospectedTable;import org.mybatis.generator.api.dom.java.*;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 Properties systemPro;private boolean suppressDate;private boolean suppressAllComments;private String currentDateStr;public MyCommentGenerator() {super();properties = new Properties();systemPro = System.getProperties();suppressDate = false;suppressAllComments = false;currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());}public void addJavaFileComment(CompilationUnit compilationUnit) {// add no file level comments by defaultreturn;}/*** Adds a suitable comment to warn users that the element was generated, and* when it was generated.*/public void addComment(XmlElement xmlElement) {return;}public void addRootComment(XmlElement rootElement) {// add no document level comments by defaultreturn;}public void addConfigurationProperties(Properties properties) {this.properties.putAll(properties);suppressDate = StringUtility.isTrue(properties.getProperty(MENT_GENERATOR_SUPPRESS_DATE));suppressAllComments = StringUtility.isTrue(properties.getProperty(MENT_GENERATOR_SUPPRESS_ALL_COMMENTS));}/*** 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*/protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {javaElement.addJavaDocLine(" *");StringBuilder sb = new StringBuilder();sb.append(" * ");sb.append(MergeConstants.NEW_ELEMENT_TAG);if (markAsDoNotDelete) {sb.append(" do_not_delete_during_merge");}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() {String result = null;if (!suppressDate) {result = currentDateStr;}return result;}public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) { if (suppressAllComments) {return;}StringBuilder sb = new StringBuilder();innerClass.addJavaDocLine("/**");sb.append(" * ");sb.append(introspectedTable.getFullyQualifiedTable());sb.append(" ");sb.append(getDateString());innerClass.addJavaDocLine(sb.toString());innerClass.addJavaDocLine(" */");}public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) { if (suppressAllComments) {return;}StringBuilder sb = new StringBuilder();innerEnum.addJavaDocLine("/**");// addJavadocTag(innerEnum, false);sb.append(" * ");sb.append(introspectedTable.getFullyQualifiedTable());innerEnum.addJavaDocLine(sb.toString());innerEnum.addJavaDocLine(" */");}public void addFieldComment(Field field, IntrospectedTable introspectedTable,IntrospectedColumn introspectedColumn) {if (suppressAllComments) {return;}StringBuilder sb = new StringBuilder();field.addJavaDocLine("/**");sb.append(" * ");sb.append(introspectedColumn.getRemarks());field.addJavaDocLine(sb.toString());// addJavadocTag(field, false);field.addJavaDocLine(" */");}public void addFieldComment(Field field, IntrospectedTable introspectedTable) {if (suppressAllComments) {return;}StringBuilder sb = new StringBuilder();field.addJavaDocLine("/**");sb.append(" * ");sb.append(introspectedTable.getFullyQualifiedTable());field.addJavaDocLine(sb.toString());field.addJavaDocLine(" */");}public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { }public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {if (suppressAllComments) {return;}// method.addJavaDocLine("/**");// addJavadocTag(method, false);// method.addJavaDocLine(" */");}public void addGetterComment(Method method, IntrospectedTable introspectedTable,IntrospectedColumn introspectedColumn) {if (suppressAllComments) {return;}method.addJavaDocLine("/**");StringBuilder sb = new StringBuilder();sb.append(" * ");sb.append(introspectedColumn.getRemarks());method.addJavaDocLine(sb.toString());sb.setLength(0);sb.append(" * @return ");sb.append(introspectedColumn.getActualColumnName());sb.append(" ");sb.append(introspectedColumn.getRemarks());method.addJavaDocLine(sb.toString());// addJavadocTag(method, false);method.addJavaDocLine(" */");}public void addSetterComment(Method method, IntrospectedTable introspectedTable,IntrospectedColumn introspectedColumn) {if (suppressAllComments) {return;}method.addJavaDocLine("/**");StringBuilder sb = new StringBuilder();sb.append(" * ");sb.append(introspectedColumn.getRemarks());method.addJavaDocLine(sb.toString());Parameter parm = method.getParameters().get(0);sb.setLength(0);sb.append(" * @param ");sb.append(parm.getName());sb.append(" ");sb.append(introspectedColumn.getRemarks());method.addJavaDocLine(sb.toString());// addJavadocTag(method, false);method.addJavaDocLine(" */");}public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {if (suppressAllComments) {return;}StringBuilder sb = new StringBuilder();innerClass.addJavaDocLine("/**");sb.append(" * ");sb.append(introspectedTable.getFullyQualifiedTable());innerClass.addJavaDocLine(sb.toString());sb.setLength(0);sb.append(" * @author ");sb.append(systemPro.getProperty(""));sb.append(" ");sb.append(currentDateStr);// addJavadocTag(innerClass, markAsDoNotDelete);innerClass.addJavaDocLine(" */");}}3.2.再新建⼀个类StartUp,⽤于运⾏项⽬,(若是集成Eclipse,可直接运⾏操作,查看mybatis与eclipse的集成,这⾥不介绍了)也就是运⾏StartUp类就会直接⽣成model,mapper以及mapper.xml,类的代码如下:package org.mybatis.generator;/*** Created by 草帽boy on 2017/2/16.* 启动⽂件,只需要点击运⾏就⾏*/import java.io.File;import java.io.IOException;import .URISyntaxException;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.exception.InvalidConfigurationException;import org.mybatis.generator.exception.XMLParserException;import org.mybatis.generator.internal.DefaultShellCallback;public class StartUp {public static void main(String[] args) throws URISyntaxException {try {List<String> warnings = new ArrayList<String>();boolean overwrite = true;//直接获取generatorConfig.xml的⽂件路径根据具体情况查看File configFile = new File("E:\\IDEAWorkPlace\\GraduationDesign\\CourseDesignManageSystem\\20170122\\CourseDesignManage\\src\\main\\resources\\generatorConfig.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);} catch (SQLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} catch (InvalidConfigurationException e) {e.printStackTrace();} catch (XMLParserException e) {e.printStackTrace();}}}3.3 另外需要简单修改⼀下generatorConfig.xml中的注释配置<commentGenerator type="org.mybatis.generator.MyCommentGenerator"><!-- <property name="suppressDate" value="true"/><!– 是否去除⾃动⽣成的注释 true:是: false:否 –><property name="suppressAllComments" value="false"/>--></commentGenerator>commentGenerator 的type是你刚刚重构的MyCommentGenerator类的位置3.4其中我的⽂件结构如下:四:点击运⾏StartUp,你会发现model,mapper以及mapper.xml都已经产⽣,其中实体类的运⾏的结果如下注意:若是出现中⽂乱码,在generatorConfig.xml⽂件中增加以下配置<property name="javaFileEncoding" value="UTF-8"/>1.以下是generatorConfig.xml配置⽂件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE generatorConfiguration PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN" "/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration ><!-- 数据库驱动包位置 --><classPathEntrylocation="D:\repository\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar"/><context id="context1"><property name="javaFileEncoding" value="UTF-8"/><commentGenerator type="com.wareic.utils.MyCommentGenerator"></commentGenerator><!-- <commentGenerator>是否去除⾃动⽣成的注释 true:是: false:否<property name="suppressAllComments" value="true"/></commentGenerator> --><!-- 数据库链接URL、⽤户名、密码 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://17.16.32.2:3306/db_wareic" userId="root" password="123456"/><!-- ⽣成模型的包名和位置 wareic为项⽬名称 --><javaModelGenerator targetPackage="com.wareic.model" targetProject="wareic/src/main/java"/><!-- ⽣成的映射⽂件报名和位置 --><sqlMapGenerator targetPackage="com.wareic.mapper" targetProject="wareic/src/main/java"/><!-- ⽣成DAO的包名和位置 --><javaClientGenerator targetPackage="com.wareic.mapper" targetProject="wareic/src/main/java" type="XMLMAPPER"/><!-- 要⽣成的那些表(更改tableName 和domainObjectName 就可以了) --><table schema="db_wareic" tableName="t_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"><!-- <columnOverride column="FILMID" property="FILMID" /> --></table></context></generatorConfiguration>2.执⾏startUp类型中的main函数3.MyBatis Generator官⽹:---------------------作者:王卫东来源:CSDN原⽂:https:///wwd0501/article/details/76618363版权声明:本⽂为博主原创⽂章,转载请附上博⽂链接!。
mybatisgenerator用法(原创版)目录1.MyBatis Generator 简介2.MyBatis Generator 的作用3.MyBatis Generator 的使用方法4.MyBatis Generator 的优点和缺点正文【MyBatis Generator 简介】MyBatis Generator 是一个基于 MyBatis 的代码生成工具,它能够根据数据库表结构自动生成相应的实体类、Mapper 接口、Service 接口以及 XML 映射文件。
通过使用 MyBatis Generator,开发者能够大大简化数据库操作的代码编写过程,提高开发效率。
【MyBatis Generator 的作用】MyBatis Generator 主要有以下几个作用:1.自动生成数据库表对应的实体类,避免了手动编写实体类的繁琐过程。
2.自动生成数据库表对应的 Mapper 接口,方便开发者进行 SQL 查询操作。
3.自动生成数据库表对应的 Service 接口,使得业务逻辑的编写更加清晰。
4.自动生成 XML 映射文件,减少了开发者编写映射文件的工作量。
【MyBatis Generator 的使用方法】使用 MyBatis Generator 的步骤如下:1.下载 MyBatis Generator 的 JAR 文件,将其添加到项目的类路径中。
2.创建一个数据库连接配置文件,指定数据库连接信息。
3.编写一个配置 XML 文件,指定生成的实体类、Mapper 接口、Service 接口以及 XML 映射文件的输出路径。
4.在命令行中执行 MyBatis Generator 的命令,根据需要指定配置文件和数据库连接配置文件的路径。
【MyBatis Generator 的优点和缺点】MyBatis Generator 的优点:1.提高了开发效率,减少了编写代码的工作量。
2.使得代码结构更加清晰,便于维护。
MybatisGenerator最完整配置详解[mybatis代码⾃动⽣成配置] Mybatis Generator最完整配置详解[mybatis代码⾃动⽣成配置]1)说明 generator配置⽂件:1.1) 配置⽣成器 :<!-- 配置⽣成器 --><generatorConfiguration>....</generatorConfiguration>1.2) ${propertyKey}引⽤${propertyKey}的⽅式来引⽤配置项:例如resource:配置资源加载地址,使⽤resource,MBG从classpath开始找,⽐如com/myproject/generatorConfig.propertiesurl:配置资源加载地质,使⽤URL的⽅式,⽐如file:///C:/myfolder/generatorConfig.properties.注意,两个属性只能选址⼀个;另外,如果使⽤了mybatis-generator-maven-plugin,那么在pom.xml中定义的properties都可以直接在generatorConfig.xml中使⽤1.3 ) classPathEntry标签【添加依赖包】<!-- 在MBG⼯作的时候,需要额外加载的依赖包,location属性指明加载jar/zip包的全路径<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />-->1.4 ) context 标签【⽣成⼀组对象的环境】<!--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" >1.5) autoDelimitKeywords 标签【⾃动识别数据的关键字】<!--⾃动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;⼀般保留默认值,遇到数据库关键字(Java关键字),使⽤columnOverride覆盖--><property name="autoDelimitKeywords" value="false"/>1.6) javaFileEncoding 标签【字符编码】<!-- ⽣成的Java⽂件的编码 --><property name="javaFileEncoding" value="UTF-8"/>1.7) javaFormatter 标签【格式化java代码】<!-- 格式化java代码 --><property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>1.8) beginningDelimiter和endingDelimiter 标签【标记数据库对象名的符号】<!-- beginningDelimiter和endingDelimiter:指明数据库的⽤于标记数据库对象名的符号,⽐如ORACLE就是双引号,MYSQL默认是`反引号; --><property name="beginningDelimiter" value="`"/><property name="endingDelimiter" value="`"/><!-- 必须要有的,使⽤这个配置链接数据库@TODO:是否可以扩展--><jdbcConnection driverClass="com.mysql.jdbc.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><!-- 在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><!-- 可以为所有⽣成的接⼝添加⼀个⽗接⼝,但是MBG只负责⽣成,不负责检查<property name="rootInterface" value=""/>--></javaClientGenerator><!-- 选择⼀个table来⽣成相关⽂件,可以有⼀个或多个table,必须要有table元素选择的table会⽣成⼀下⽂件:1,SQL map⽂件2,⽣成⼀个主键类;3,除了BLOB和主键的其他字段的类;4,包含BLOB的类;5,⼀个⽤户⽣成动态查询的条件类(selectByExample, deleteByExample),可选;6,Mapper接⼝(可选)tableName(必要):要⽣成对象的表名;注意:⼤⼩写敏感问题。
mybatis generator 自定义方法MyBatis Generator 是一个用于生成 MyBatis 映射文件和代码的工具。
它可以根据数据库表结构自动生成相应的 Java 实体类、Mapper 接口和 XML 映射文件。
如果你想要在 MyBatis Generator 中自定义一些方法,可以通过以下步骤来实现:1. 创建一个自定义的 MyBatis Generator 插件。
插件是 MyBatis Generator 的扩展点,可以通过插件来实现自定义的功能。
2. 在插件中实现自己的方法。
你可以在插件的代码中添加自己的方法,这些方法可以在生成代码的过程中被调用。
3. 在 MyBatis Generator 的配置文件中配置插件。
在配置文件中添加插件的配置信息,让 MyBatis Generator 在生成代码时加载你的插件。
下面是一个简单的示例,演示如何在 MyBatis Generator 中自定义一个方法:1. 创建一个自定义的 MyBatis Generator 插件,命名为CustomGeneratorPlugin。
```javapublic class CustomGeneratorPlugin extends DefaultGeneratorPlugin {@Overridepublic boolean validate(List<String> warnings) {// 在这里添加自定义的验证逻辑return true;}@Overridepublic boolean modelBaseRecordHasId(JTable table) {// 在这里添加自定义的逻辑,判断实体类是否有主键return true;}@Overridepublic boolean modelPrimaryKeyClassHasId(JTable table) { // 在这里添加自定义的逻辑,判断实体类的主键类是否有id 属性return true;}@Overridepublic boolean modelPrimaryKey ClassHasIdField(JTable table, JClass jClass) {// 在这里添加自定义的逻辑,判断实体类的主键类是否有id 属性字段return true;}}```2. 在 MyBatis Generator 的配置文件中配置插件。
Java框架中的代码生成工具介绍代码生成工具在Java框架中扮演着重要的角色,它们可以自动创建模板代码和基础结构,大大提高了开发效率。
本文将介绍几种常用的Java框架中的代码生成工具。
一、MyBatis-GeneratorMyBatis-Generator是一款强大的代码生成工具,主要用于生成与数据库表对应的实体类、DAO类、Mapper映射文件等。
它基于MyBatis框架,可以根据数据库的结构自动生成相应的代码。
使用MyBatis-Generator非常简单,只需编写一个XML配置文件,指定数据库连接信息、表名、生成代码的目录等,就可以自动生成所需的代码。
可以通过自定义插件来扩展其功能,满足不同项目的需求。
二、Spring RooSpring Roo是一个开源的Rapid Application Development(快速应用开发)工具,它可以快速生成基于Spring框架的Java应用的骨架代码。
Spring Roo可以通过命令行或者图形界面进行操作,提供了丰富的命令和选项来生成代码、配置文件等。
使用Spring Roo可以轻松地创建实体类、控制器、服务层等,并自动处理相关的依赖注入、持久化等问题。
它还支持自定义代码模板和插件,方便定制化开发。
三、JHipsterJHipster是一款用于生成现代化Java应用程序的代码生成器。
它结合了Java、Spring Boot、Angular/React/Vue.js等技术,可以快速构建全栈应用。
借助JHipster,开发人员可以选择不同的选项,如数据库类型、身份验证模块、前端框架等,然后通过一条命令生成项目的基础结构和代码。
生成的代码包括实体类、RESTful API、前端页面等,大大减少了开发工作量。
四、Apache VelocityApache Velocity是一款基于Java的模板引擎,也可以用作代码生成工具。
它使用简单且功能强大,可以根据自定义的模板生成任意文本文件。
mybatis-generator⾃动⽣成代码(lombok带注释)最近接触到的项⽬都会⽤到mybatis框架,会涉及到实体和表的映射,mapper以及mapper.xml的⽣成,mybatis-generator插件可以根据表结构⾃动⽣成实体、mapper、mapper.xml,⼤⼤简化了开发的⼯作量,现有的插件有点⼩缺陷,注释没有获取数据库字段的注释(mysql为例就是字段的comment),包括不⽀持lombok。
查阅相关资料,我这边修改了下mybatis-generator-core-1.3.7.jar包,⽣成的实体取数据库注释,并⽀持lombok,废话不多说,先看下效果。
建表语句:CREATE TABLE `t_person` (`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '⾃增ID',`name` varchar(50) NOT NULL COMMENT '姓名',`nick` varchar(50) NOT NULL COMMENT '昵称',`sex` varchar(50) NOT NULL COMMENT '性别',`age` int(5) NOT NULL COMMENT '年龄',`create_time` datetime NOT NULL COMMENT '创建时间',`modify_time` datetime DEFAULT NULL COMMENT '最后修改时间',PRIMARY KEY (`id`) USING BTREE) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='⽤户表';⽣成的实体类package com.sicent.firm.bean;import java.util.Date;import lombok.Data;/*** t_person* @author yl.bu* @date 2019-05-30 22:01:47*/@Datapublic class Person {/*** ⾃增ID*/private Long id;/*** 姓名*/private String name;/*** 昵称*/private String nick;/*** 性别*/private String sex;/*** 年龄*/private Integer age;/*** 创建时间*/private Date createTime;/*** 最后修改时间*/private Date modifyTime;}下⾯讲⼀下实现⽅式:第⼀步:新建类MyBatisPlugin 继承 PluginAdapter,如下所⽰package org.mybatis.generator.plugins;import java.util.Date;import java.util.List;import ng3.time.DateFormatUtils;import org.mybatis.generator.api.IntrospectedColumn;import org.mybatis.generator.api.IntrospectedTable;import org.mybatis.generator.api.PluginAdapter;import org.mybatis.generator.api.dom.java.Field;import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;import org.mybatis.generator.api.dom.java.Interface;import org.mybatis.generator.api.dom.java.Method;import org.mybatis.generator.api.dom.java.TopLevelClass;import org.mybatis.generator.internal.util.StringUtility;/*** @ClassName: MyBatisPlugin* @Description: mybatis-generator注释插件* @author buyl* @date 2019年5⽉30⽇上午22:04:55* @Version V1.0*/public class MyBatisPlugin extends PluginAdapter {@Overridepublic boolean validate(List<String> list) {return true;}@Overridepublic boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {boolean hasLombok = Boolean.parseBoolean(getProperties().getProperty("hasLombok", "false"));System.out.println("hasLombok" + hasLombok);if (hasLombok) {// 添加domain的importtopLevelClass.addImportedType("lombok.Data");// 添加domain的注解topLevelClass.addAnnotation("@Data");}topLevelClass.addJavaDocLine("/**");String remarks = introspectedTable.getRemarks();if (StringUtility.stringHasValue(remarks)) {String[] remarkLines = remarks.split(System.getProperty("line.separator"));for (String remarkLine : remarkLines) {topLevelClass.addJavaDocLine(" * " + remarkLine);}}StringBuilder sb = new StringBuilder();sb.append(" * ").append(introspectedTable.getFullyQualifiedTable());topLevelClass.addJavaDocLine(sb.toString());sb.setLength(0);sb.append(" * @author ").append(System.getProperties().getProperty(""));topLevelClass.addJavaDocLine(sb.toString());sb.setLength(0);sb.append(" * @date ");sb.append(getDateString());topLevelClass.addJavaDocLine(sb.toString());topLevelClass.addJavaDocLine(" */");return true;}@Overridepublic boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,IntrospectedTable introspectedTable, ModelClassType modelClassType) {field.addJavaDocLine("/**");String remarks = introspectedColumn.getRemarks();if (StringUtility.stringHasValue(remarks)) {String[] remarkLines = remarks.split(System.getProperty("line.separator"));for (String remarkLine : remarkLines) {field.addJavaDocLine(" * " + remarkLine);}}field.addJavaDocLine(" */");return true;}@Overridepublic boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {// 添加Mapper的importinterfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper"));// 添加Mapper的注解interfaze.addAnnotation("@Mapper");return true;}@Overridepublic boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {// 不⽣成getterboolean hasLombok = Boolean.parseBoolean(getProperties().getProperty("hasLombok", "false"));return !hasLombok;}@Overridepublic boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {// 不⽣成setterboolean hasLombok = Boolean.parseBoolean(getProperties().getProperty("hasLombok", "false"));return !hasLombok;}protected String getDateString() {return DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");}}第⼆步:压缩解压⼯具打开mybatis-generator-core-1.3.7.jar, 拷贝第⼀步编译后的class⽂件即MyBatisPlugin.class到org.mybatis.generator.plugins下,第三步:pom依赖,mybatis-generator-core-1.3.7.jar需要为上⾯替换过的,如果只能⽤原来的mybatis-generator-core-1.3.7.jar,只需要把第⼀步的java代码拷贝⼀份到项⽬中即可(有不懂得可以下来咨询我)<dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.7</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency>第四步:配置generatorConfig.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN""/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><!-- 引⼊mysql-connector-java-5.1.47.jar位置 --><classPathEntrylocation="D:/workspaces/workspace/z-mybatis-generator/lib/mysql-connector-java-5.1.47.jar"/><!-- 是否去除⾃动⽣成的注释 true:是: false:否 --><context id="DB2Tables" targetRuntime="MyBatis3"><plugin type="org.mybatis.generator.plugins.MyBatisPlugin"><property name="hasLombok" value="true"/></plugin><commentGenerator><property name="suppressAllComments" value="true"/></commentGenerator><jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/test" userId="root" password="123456"></jdbcConnection><!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和NUMERIC 类型解析为java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false"/></javaTypeResolver><!-- ⽣成model模型,对应的包路径,以及⽂件存放路径(targetProject),targetProject可以指定具体的路径也可以使⽤“MAVEN”来⾃动⽣成,这样⽣成的代码会在target/generatord-source⽬录下 --> <javaModelGenerator targetPackage="com.sicent.firm.bean" targetProject="z-mybatis-generator"><property name="enableSubPackages" value="true"/><!-- 从数据库返回的值被清理前后的空格 --><property name="trimStrings" value="true"/></javaModelGenerator><!--对应的mapper.xml⽂件 --><sqlMapGenerator targetPackage="com.sicent.firm.dao" targetProject="z-mybatis-generator"><property name="enableSubPackages" value="true"/></sqlMapGenerator><!-- 对应的Mapper接⼝类⽂件 --><javaClientGenerator type="XMLMAPPER" targetPackage="com.sicent.firm.dao" targetProject="z-mybatis-generator"><property name="enableSubPackages" value="true"/></javaClientGenerator><table tableName="t_person" domainObjectName="Person"enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="false"enableSelectByExample="true" selectByExampleQueryId="false"><property name="useActualColumnNames" value="false"/></table></context></generatorConfiguration>关键的地⽅就是配置插件:<plugin type="org.mybatis.generator.plugins.MyBatisPlugin"><property name="hasLombok" value="true"/></plugin>第五步:执⾏命令 java -jar mybatis-generator-core-1.3.7.jar -configfile generatorConfig.xml -overwrite或者eclipse或者idea安装mybatis-generator插件运⾏插件安装以及其他涉及到的我就不详细讲了,有问题可随时找我。
mybatis-generator-core⾃动⽣成实体和Mapper所谓mybatis-generator-core就是利⽤mybatis-generator-core.jar⾃动⽣成数据库对应的实体和映射⽂件。
⾸先要下载。
1.然后创建⼀个⽂件夹我们定义为mybatis。
在mybatis⾥⾯创建lib和src两个⽂件夹。
同时将mybatis-generator-core-1.3.2.zip解压后的jar⽂件放到mybatis⽂件夹中。
2.将mysql的jar包拷贝到lib⽬录下,mysql-connector-java-5.1.43.jar。
注意不要⽤6.x版本。
可能会出问题。
3.然后就是在mybatis⾥⾯创建xml⽂件generator.xml。
内容如下:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN" "/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><!-- 数据库驱动包位置 --><!-- <classPathEntry location="D:\software\lib\mysql-connector-java-5.1.21.jar" /> --><classPathEntry location=".\lib\mysql-connector-java-5.1.43.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/sy" userId="sypro" password="sypro"> --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://172.23.88.107:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"userId="root"password="zdsoft"></jdbcConnection><javaTypeResolver><property name="forceBigDecimals" value="false"/></javaTypeResolver><!-- ⽣成模型的包名和位置 --><javaModelGenerator targetPackage="cn.duanjt.ssm.entity" targetProject=".\src"><property name="enableSubPackages" value="true"/><property name="trimStrings" value="true"/></javaModelGenerator><!-- ⽣成的映射⽂件包名和位置 --><sqlMapGenerator targetPackage="cn.duanjt.ssm.mapper" targetProject=".\src"><property name="enableSubPackages" value="true"/></sqlMapGenerator><!-- ⽣成DAO的包名和位置 --><javaClientGenerator type="XMLMAPPER" targetPackage="cn.duanjt.ssm.dao" targetProject=".\src"><property name="enableSubPackages" value="true"/></javaClientGenerator><!--要⽣成那些表(更改tableName和domainObjectName就可以)domainObjectName表⽰实体对象的名称,不指定将⾃动⽣成--><table tableName="Student" domainObjectName="" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"<table tableName="stat_app" domainObjectName="" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" </context></generatorConfiguration>然后就是在mybatis⽬录下打开dos程序,然后执⾏代码:java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite出现如下界⾯表⽰成功:说明:1.src⽬录必须存在,否则要抛异常2.mysql的jar包版本不要⽤6.x。
Mybatis使用generator自动生成映射配置文件信息
分类:JavaEE框架 2015-01-24 17:51 3431人阅读评论(2) 收藏举报
使用mybatis配置映射文件比较的麻烦,但是有自动生成jar工具,方便加速开发速度,下面主要是该工具的使用以及相关的配置。
1、下载相关的资源
我们需要下载mybatis-generator-core-1.3.2.jar,mysql-connector-java-5.1.34.jar(对应相关数据库的驱动包),generator.xml (配置文件)
我的网盘全部相关下载地址:/s/1ntn48pb
文件结构为:
2、配置generator.xml文件
[html]view plaincopy
1.<?xml version="1.0" encoding="UTF-8"?>
2.<!DOCTYPE generatorConfiguration PUBLIC "-
////DTD MyBatis Generator Configuration 1.0//EN"
"/dtd/mybatis-generator-
config_1_0.dtd">
3.<generatorConfiguration>
4.<!-- 数据库驱动包位置-->
5.<classPathEntry location="D:\generator\mysql-
connector-java-5.1.34.jar" />
6.<!--
<classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc \lib\ojdbc14.jar" />-->
7.<context id="DB2Tables" targetRuntime="MyBatis3">
8.<commentGenerator>
9.<property name="suppressAllComments"
value="true" />
10. </commentGenerator>
11. <!-- 数据库链接URL、用户名、密码-->
12. <jdbcConnection driverClass="com.mysql.jdbc.
Driver" connectionURL="jdbc:mysql://localhost:3306/shop" user Id="root" password="12345">
13. <!--
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId ="msa" password="msa">-->
14. </jdbcConnection>
15. <javaTypeResolver>
16. <property name="forceBigDecimals" val
ue="false" />
17. </javaTypeResolver>
18. <!-- 生成模型的包名和位置-->
19. <javaModelGenerator targetPackage="andy.model"
targetProject="D:\generator\src">
20. <property name="enableSubPackages" va
lue="true" />
21. <property name="trimStrings" value="t
rue" />
22. </javaModelGenerator>
23. <!-- 生成的映射文件包名和位置-->
24. <sqlMapGenerator targetPackage="andy.mapping"
targetProject="D:\generator\src">
25. <property name="enableSubPackages" va
lue="true" />
26. </sqlMapGenerator>
27. <!-- 生成DAO的包名和位置-->
28. <javaClientGenerator type="XMLMAPPER" targetP
ackage="andy.dao" targetProject="D:\generator\src">
29. <property name="enableSubPackages" va
lue="true" />
30. </javaClientGenerator>
31. <!-- 要生成那些表(更改tableName和
domainObjectName就可以) -->
32. <table tableName="user_info" domainObjectName
="UserInfo" enableCountByExample="false" enableUpdateByExampl e="false" enableDeleteByExample="false" enableSelectByExample ="false" selectByExampleQueryId="false" />
33. <table tableName="course_info" domainObjectNa
me="CourseInfo" enableCountByExample="false" enableUpdateByEx ample="false" enableDeleteByExample="false" enableSelectByExa mple="false" selectByExampleQueryId="false" />
34. <table tableName="course_user_info" domainObj
ectName="CourseUserInfo" enableCountByExample="false" enableU pdateByExample="false" enableDeleteByExample="false" enableSe lectByExample="false" selectByExampleQueryId="false" />
35. </context>
36.</generatorConfiguration>
需要修改对应数据库的驱动文件位置,以数据库名密码。
设置对应的生成表的表名以及对应的类名,这样就自动生成了model,dao,mappding配置文件。
3、生成配置文件
打开cmd,进入目录generator,执行命令
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
执行完后就自动生成dao,mapping,model文件内容了。