热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Mybatis自动生成实体与Mapper工具类

随着MyBatis越来越深入人心,那么在使用Mybatis的时候,最最最麻烦的,莫过于是写Mapper。幸好,万能的程序猿们

随着MyBatis越来越深入人心,那么在使用Mybatis的时候,最最最麻烦的,莫过于是写Mapper。
幸好,万能的程序猿们已经开发出一套方便的工具,根据已有的数据库表来生成对应的JavaBean以及相应的一些Mapper

项目下载地址[]

两个关键类
1、Generator类,程序入口


import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;/*** 数据库实体类生成器** @Autor Shadow 2020/12/9* @Date 2020-12-09 10:32:55*/
public class Generator {public static void main(String[] args) throws Exception {//MBG 执行过程中的警告信息List<String> warnings &#61; new ArrayList<String>();//当生成的代码重复时&#xff0c;覆盖原代码boolean overwrite &#61; true;//读取我们的 MBG 配置文件InputStream is &#61; Generator.class.getResourceAsStream("/generatorConfig.xml");ConfigurationParser cp &#61; new ConfigurationParser(warnings);Configuration config &#61; cp.parseConfiguration(is);is.close();DefaultShellCallback callback &#61; new DefaultShellCallback(overwrite);//创建 MBGMyBatisGenerator myBatisGenerator &#61; new MyBatisGenerator(config, callback, warnings);//执行生成代码myBatisGenerator.generate(null);//输出警告信息for (String warning : warnings) {System.out.println(warning);}}
}

2、MyCommentGenerator注解生成类


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.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;import java.util.Properties;/*** 自定义注释生成器* Created by macro on 2018/4/26.*/
public class MyCommentGenerator extends DefaultCommentGenerator {private boolean addRemarkComments &#61; false;private static final String EXAMPLE_SUFFIX &#61; "Example";private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME &#61; "io.swagger.annotations.ApiModelProperty";/*** 设置用户配置的参数*/&#64;Overridepublic void addConfigurationProperties(Properties properties) {super.addConfigurationProperties(properties);this.addRemarkComments &#61; StringUtility.isTrue(properties.getProperty("addRemarkComments"));}/*** 给字段添加注释*/&#64;Overridepublic void addFieldComment(Field field, IntrospectedTable introspectedTable,IntrospectedColumn introspectedColumn) {String remarks &#61; introspectedColumn.getRemarks();//根据参数和备注信息判断是否添加备注信息if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
// addFieldJavaDoc(field, remarks);//数据库中特殊字符需要转义if (remarks.contains("\"")) {remarks &#61; remarks.replace("\"", "&#39;");}addFieldJavaDoc(field, remarks);//给model的字段添加swagger注解field.addJavaDocLine("&#64;ApiModelProperty(value &#61; \"" &#43; remarks &#43; "\")");}}/*** 给model的字段添加注释*/private void addFieldJavaDoc(Field field, String remarks) {//文档注释开始field.addJavaDocLine("/**");//获取数据库字段的备注信息String[] remarkLines &#61; remarks.split(System.getProperty("line.separator"));for (String remarkLine : remarkLines) {field.addJavaDocLine(" * " &#43; remarkLine);}
// addJavadocTag(field, false);field.addJavaDocLine(" */");}&#64;Overridepublic void addJavaFileComment(CompilationUnit compilationUnit) {super.addJavaFileComment(compilationUnit);//只在model中添加swagger注解类的导入if (!compilationUnit.isJavaInterface() && !compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)) {compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));}}
}

3、配置文件 generatorConfig.xml


<generatorConfiguration><properties resource&#61;"generator.properties"/><context id&#61;"MySqlContext" targetRuntime&#61;"MyBatis3" defaultModelType&#61;"flat"><property name&#61;"beginningDelimiter" value&#61;"&#96;"/><property name&#61;"endingDelimiter" value&#61;"&#96;"/><property name&#61;"javaFileEncoding" value&#61;"UTF-8"/><plugin type&#61;"org.mybatis.generator.plugins.SerializablePlugin"/><plugin type&#61;"org.mybatis.generator.plugins.ToStringPlugin"/><plugin type&#61;"org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/><commentGenerator type&#61;"xxx.xxx.xxx.MyCommentGenerator"><property name&#61;"suppressAllComments" value&#61;"true"/><property name&#61;"suppressDate" value&#61;"true"/><property name&#61;"addRemarkComments" value&#61;"true"/>commentGenerator><jdbcConnection driverClass&#61;"${jdbc.driverClass}"connectionURL&#61;"${jdbc.connectionURL}"userId&#61;"${jdbc.username}"password&#61;"${jdbc.password}"><property name&#61;"nullCatalogMeansCurrent" value&#61;"true"/>jdbcConnection><javaModelGenerator targetPackage&#61;"xxx.xxx.xxx.entity" targetProject&#61;"xxx-project/src/main/java"/><sqlMapGenerator targetPackage&#61;"xxx.xxx.xxx.mapper" targetProject&#61;"xxx-project/src/main/resources"/><javaClientGenerator type&#61;"XMLMAPPER" targetPackage&#61;"xxx.xxx.xxx.mapper"targetProject&#61;"xxx-project/src/main/java"/><table tableName&#61;"%"><generatedKey column&#61;"id" sqlStatement&#61;"MySql" identity&#61;"true"/>table>context>
generatorConfiguration>

4、generator.properties文件

jdbc.driverClass&#61;com.mysql.cj.jdbc.Driver
jdbc.connectionURL&#61;jdbc:mysql://127.0.0.1:3306/xxxxx?useUnicode&#61;true&characterEncoding&#61;utf-8&serverTimezone&#61;Asia/Shanghai
jdbc.username&#61;root
jdbc.password&#61;123456

5、pom文件 关键依赖&#xff08;我这里是引入parent-module 所以版本写在其它地方 这里自己找对应版本就好&#xff09;

<dependencies><dependency><groupId>io.springfoxgroupId><artifactId>springfox-swagger-commonartifactId><version>2.9.2version>dependency><dependency><groupId>com.github.pagehelpergroupId><artifactId>pagehelper-spring-boot-starterartifactId><version>1.2.10version>dependency><dependency><groupId>com.alibabagroupId><artifactId>druid-spring-boot-starterartifactId><version>1.1.10version>dependency><dependency><groupId>org.mybatis.generatorgroupId><artifactId>mybatis-generator-coreartifactId><version>1.3.7version>dependency><dependency><groupId>mysqlgroupId><artifactId>mysql-connector-javaartifactId><version>8.0.20version>dependency>dependencies>

效果

生成的Entity
在这里插入图片描述
2、生成的Mapper
在这里插入图片描述


推荐阅读
author-avatar
今日屎汰濃
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有