Mybatis generator生成工具简单介绍
Mybatis generator
其主要的功能就是方便,快捷的创建好Dao,entry,xml 加快了开发速度,使用方面根据其提供的规则配置好就OK
这里还有一个重要的开发场景,开发过程中,对数据库的操作肯定很多,比如新增字段什么的,你只要将原先自动生成的一套代码删除,重新再生成一份,这就完美解决了,但是这样做的前提是,你必须对生成后的代码不改动,只是使用。不需要想手动开发写代码那样到处改代码,还担心改漏地方。
其实这个的实现方式也是五花八门的,写一种比较常见的
主要流程
第一步:添加依赖
主要是jdbc和generator
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
第二步:配置 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>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 生成mysql带有分页的sql的插件 这个可以自己写,-->
<plugin type="generator.MysqlPaginationPlugin" />
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<!-- 自定义的注释规则,继承 DefaultCommentGenerator 重写 一些方法 -->
<commentGenerator type="generator.NewbatisGenerator">
<!-- 是否去除自动生成日期的注释 true:是 : false:否 -->
<property name="suppressDate" value="true"/>
<!-- 是否去除所有自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://数据库地址"
userId="username"
password="password">
</jdbcConnection>
<!--生成entity类存放位置-->
<javaModelGenerator targetPackage="包名(com.generator.test.entity)" targetProject="项目地址到\java (D:\workspace\src\main\java)">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成映射文件存放位置-->
<sqlMapGenerator targetPackage="包名(com.generator.test.mapper)" targetProject="项目地址到\java (D:\workspace\src\main\java)">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--生成Dao类存放位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="包名(com.generator.test.dao)"
targetProject="项目地址到\java (D:\workspace\src\main\java)">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="表名" domainObjectName="生成实体的类名">
</table>
</context>
</generatorConfiguration>
第三步:主要看你个人的需求,对注释,分页啥的有啥要求不,可以重写几个方法对其进行改造
主要举几个例子
对注释的修改 NewbatisGenerator
public class NewbatisGenerator extends DefaultCommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String currentDateStr;
public NewbatisGenerator() {
super();
properties = new Properties();
systemPro = System.getProperties();
suppressDate = false;
suppressAllComments = false;
currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
}
/**
* 对类的注解
* @param topLevelClass
* @param introspectedTable
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * 这是MyBatis Generator自动生成的Model Class.");
StringBuilder sb = new StringBuilder();
sb.append(" * 对应的数据表是 : ");
sb.append(introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(sb.toString());
String tableRemarks = introspectedTable.getRemarks();
if (!StringUtils.isEmpty(tableRemarks)) {
sb.setLength(0);
sb.append(" * 数据表注释 : ");
sb.append(tableRemarks);
topLevelClass.addJavaDocLine(sb.toString());
}
sb.setLength(0);
sb.append(" * @author ");
sb.append(systemPro.getProperty("user.name"));
topLevelClass.addJavaDocLine(sb.toString());
String curDateString = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
sb.setLength(0);
sb.append(" * @date ");
sb.append(curDateString);
topLevelClass.addJavaDocLine(sb.toString());
topLevelClass.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().replace("\n", " "));
field.addJavaDocLine(" */");
}
}
对分页的添加 MysqlPaginationPlugin 自动生成带分页插件
public class MysqlPaginationPlugin extends PluginAdapter {
public MysqlPaginationPlugin() {}
public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
this.addLimit(topLevelClass, introspectedTable, "limitStart");
this.addLimit(topLevelClass, introspectedTable, "limitSize");
return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
}
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element,
IntrospectedTable introspectedTable) {
XmlElement isNotNullElement = new XmlElement("if");
isNotNullElement
.addAttribute(new Attribute("test", "limitStart != null and limitSize >= 0"));
isNotNullElement.addElement(new TextElement("limit #{limitStart} , #{limitSize}"));
element.addElement(isNotNullElement);
return super.sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
}
public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element,
IntrospectedTable introspectedTable) {
XmlElement isNotNullElement = new XmlElement("if");
isNotNullElement
.addAttribute(new Attribute("test", "limitStart != null and limitSize >= 0"));
isNotNullElement.addElement(new TextElement("limit #{limitStart} , #{limitSize}"));
element.addElement(isNotNullElement);
return super.sqlMapSelectByExampleWithBLOBsElementGenerated(element, introspectedTable);
}
private void addLimit(TopLevelClass topLevelClass, IntrospectedTable introspectedTable,
String name) {
CommentGenerator commentGenerator = this.context.getCommentGenerator();
Field field = new Field();
field.setVisibility(JavaVisibility.PROTECTED);
field.setType(PrimitiveTypeWrapper.getIntegerInstance());
field.setName(name);
commentGenerator.addFieldComment(field, introspectedTable);
topLevelClass.addField(field);
char c = name.charAt(0);
String camel = Character.toUpperCase(c) + name.substring(1);
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setName("set" + camel);
method.addParameter(new Parameter(PrimitiveTypeWrapper.getIntegerInstance(), name));
StringBuilder sb = new StringBuilder();
sb.append("this.");
sb.append(name);
sb.append(" = ");
sb.append(name);
sb.append(";");
method.addBodyLine(sb.toString());
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
Method getterMethod = AbstractJavaGenerator.getGetter(field);
commentGenerator.addGeneralMethodComment(getterMethod, introspectedTable);
topLevelClass.addMethod(getterMethod);
}
public boolean validate(List<String> warnings) {
return true;
}
/**
* 生成mapper.xml,文件内容会被清空再写入
* */
@Override
public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
sqlMap.setMergeable(false);
return super.sqlMapGenerated(sqlMap, introspectedTable);
}
}
最后一步:运行生成
这些官网都是有的
public class Generator {
public static void main(String[] args) throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("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);
}
}
这个比较简单明了,个性化也不错,值得推荐
转载请注明出处:https://www.cnblogs.com/zhouguanglin/p/11239583.html
Mybatis generator生成工具简单介绍的更多相关文章
- Mybatis Generator生成工具配置文件详解
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...
- MyBatis Generator 生成的example 使用 and or 简单混合查询
MyBatis Generator 生成的example 使用 and or 简单混合查询 参考博客:https://www.cnblogs.com/kangping/p/6001519.html 简 ...
- mybatis Generator生成代码及使用方式
本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5889312.html 为什么要有mybatis mybatis 是一个 Java 的 ORM 框架,OR ...
- 「小程序JAVA实战」Springboot版mybatis逆向生成工具(32)
转自:https://idig8.com/2018/08/29/xiaochengxujavashizhanspringbootbanmybatisnixiangshengchenggongju32/ ...
- 【记录】Mybatis Generator生成数据对象Date/TimeStamp 查询时间格式化
Mybatis Generator是很好的工具帮助我们生成表映射关联代码,最近博主遇到一个问题,找了很久才解决, 就是用Mybatis Generator生成实体类的时候,Date 时间无法格式化输出 ...
- 【转载】JMeter学习(一)工具简单介绍
JMeter学习(一)工具简单介绍 一.JMeter 介绍 Apache JMeter是100%纯JAVA桌面应用程序,被设计为用于测试客户端/服务端结构的软件(例如web应用程序).它可以用来测试静 ...
- Maven下用MyBatis Generator生成文件
使用Maven命令用MyBatis Generator生成MyBatis的文件步骤如下: 1.在mop文件内添加plugin <build> <finalName>KenShr ...
- JMeter学习工具简单介绍
JMeter学习工具简单介绍 一.JMeter 介绍 Apache JMeter是100%纯JAVA桌面应用程序,被设计为用于测试客户端/服务端结构的软件(例如web应用程序).它可以用来测试静态 ...
- MyBatis Generator生成DAO——序列化
MyBatis Generator生成DAO 的时候,生成的类都是没有序列化的. 还以为要手工加入(開始是手工加入的),今天遇到分页的问题,才发现生成的时候能够加入插件. 既然分页能够有插件.序列化是 ...
随机推荐
- 所有W版本的函数都在wchar.h文件(_wfopen),和stdlib.h文件(wcstombs),和stdio.h文件(vwprintf)
C:\Qt\Qt5.6.2\Tools\mingw492_32\i686-w64-mingw32\include\wchar.h C:\Qt\Qt5.6.2\Tools\mingw492_32\i68 ...
- Qt 5.6.0 动态编译(VS2013 x86 target xp openssl icu webkit)
经历了多次延期后,在3月16号,Qt发布了5.6.0版本(全面支持高DPI无疑是一个亮点),从5.6.0版本开始,Qt直接移除了webkit模块,让webengine作为其替代选择,不过webengi ...
- 每天进步一点--WCF学习笔记
最近买了一本书WCF服务编程,重头再开始了解学习WCF,现将学习记录,以便后来复习,也希望和大家一起进步. WCF用终结点表示一种组成关系,终结点就是地址.契约与绑定的混合品,即 地址(Address ...
- 跨平台网络通信与服务器框架 acl 3.2.0 发布,acl_cpp 是基于 acl 库的 C++ 库
acl 3.2.0 版本发布了,acl 是 one advanced C/C++ library 的简称,主要包括网络通信库以及服务器框架库等功能,支持 Linux/Windows/Solaris/F ...
- C++ Builder 控件的卸载
控件卸载: 1.选择 BCB 菜单 File→Close All (关闭所有文件) 选择BCB 菜单: Project→Options→Packages 在 ...
- LFS Linux From Scratch 笔记(经验非教程)
做了一个自己的DIY Linux系统.从编译每一行代码,建立每一个文件系统结构开始. 创造自己的GNU/Linux系统,不同于任何发行版.按照的教程是来自 linuxfromscratch.org 来 ...
- 【数据结构】31、hashmap=》resize 扩容,不测不知道,一测吓一跳
来来来,今天就跟hashmap杠到底... 不要叫我杠精了,主要是还是被问到hashmap的时候,我并不能很清晰明了得告知这种数据结构到底是一个什么构造,里面细节并不了解 既然这样,我们就把他解析一波 ...
- Python实现按键精灵(二)-找图找色
一.实现功能 判断在指定坐标范围内,是否存在相似度大于n的图片,并返回坐标. 二.基本思路 A=你需要寻找的图片 B=截取当前页面中指定范围的图片 利用opencv 判断A在B中的位置, 在该位置截取 ...
- 玩转java多线程(wait和notifyAll的正确使用姿势)
转载请标明博客的地址 本人博客和github账号,如果对你有帮助请在本人github项目AioSocket上点个star,激励作者对社区贡献 个人博客:https://www.cnblogs.com/ ...
- mvc中Scripts.Render的用法
第一次接触新的东西,都会很陌生,但是时间久了就熟悉了变简单了. 视图文件中使用Scripts.Render()输出脚本包,Styles.Render()输出样式包 上面两张图是我所做项目里的,放上面会 ...