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生成工具简单介绍的更多相关文章

  1. Mybatis Generator生成工具配置文件详解

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...

  2. MyBatis Generator 生成的example 使用 and or 简单混合查询

    MyBatis Generator 生成的example 使用 and or 简单混合查询 参考博客:https://www.cnblogs.com/kangping/p/6001519.html 简 ...

  3. mybatis Generator生成代码及使用方式

    本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5889312.html 为什么要有mybatis mybatis 是一个 Java 的 ORM 框架,OR ...

  4. 「小程序JAVA实战」Springboot版mybatis逆向生成工具(32)

    转自:https://idig8.com/2018/08/29/xiaochengxujavashizhanspringbootbanmybatisnixiangshengchenggongju32/ ...

  5. 【记录】Mybatis Generator生成数据对象Date/TimeStamp 查询时间格式化

    Mybatis Generator是很好的工具帮助我们生成表映射关联代码,最近博主遇到一个问题,找了很久才解决, 就是用Mybatis Generator生成实体类的时候,Date 时间无法格式化输出 ...

  6. 【转载】JMeter学习(一)工具简单介绍

    JMeter学习(一)工具简单介绍 一.JMeter 介绍 Apache JMeter是100%纯JAVA桌面应用程序,被设计为用于测试客户端/服务端结构的软件(例如web应用程序).它可以用来测试静 ...

  7. Maven下用MyBatis Generator生成文件

    使用Maven命令用MyBatis Generator生成MyBatis的文件步骤如下: 1.在mop文件内添加plugin <build> <finalName>KenShr ...

  8. JMeter学习工具简单介绍

    JMeter学习工具简单介绍   一.JMeter 介绍 Apache JMeter是100%纯JAVA桌面应用程序,被设计为用于测试客户端/服务端结构的软件(例如web应用程序).它可以用来测试静态 ...

  9. MyBatis Generator生成DAO——序列化

    MyBatis Generator生成DAO 的时候,生成的类都是没有序列化的. 还以为要手工加入(開始是手工加入的),今天遇到分页的问题,才发现生成的时候能够加入插件. 既然分页能够有插件.序列化是 ...

随机推荐

  1. 更改当前电源策略(使用SetActivePwrScheme API函数),自定义电源按钮动作(设置GLOBAL_POWER_POLICY)

    #include <windows.h> #include <Powrprof.h> #pragma comment(lib, "Powrprof.lib" ...

  2. C#WinForm线程基类

    在CS模式开发中一般我们需要用到大量的线程来处理比较耗时的操作,以防止界面假死带来不好的体验效果,下面我将我定义的线程基类给大家参考下,如有问题欢迎指正. 基类代码 #region 方法有返回值 // ...

  3. 京东sdk商家上架接口调用问题总结

    前言: 最近在做商家发布产品,调用京东sdk,发现问题很多,而且还是在我同事的帮助下完成的,摸索中,菜鸟还请高手门多多提携才好,入正题 首先是引用jd的sdk啦,京东sdk中发布商品需要调用一个 36 ...

  4. QThread多线程编程经典案例分析(三种方法,解释了为什么使用moveToThread的根本原因,即为了避免调用QThread::exec() )

    传统的图形界面应用程序都只有一个线程执行,并且一次执行一个操作.如果用户调用一个比较耗时的操作,就会冻结界面响应. 一个解决方法是按照事件处理的思路: 调用 Void QApplication::pr ...

  5. Codility---Nesting

    Task description A string S consisting of N characters is called properly nested if: S is empty; S h ...

  6. C语言实现常用数据结构——栈

    #include<stdio.h> #include<stdlib.h> //用链表实现栈 typedef struct Node { int data; struct Nod ...

  7. 简单有趣的hover

    一张图片在鼠标悬浮的时候换另一张图片 平常写张图片用img我们换一种方法用背景,然后就悬浮出 我们在加个边框试试 怎么才能让边框一起换哪? 我们嵌套一下 然后打开就是 是不是一个很简单的hover

  8. 错误处理之try、catch、finally中的return、throw执行顺序。

    今天遇到一个让人无语的代码块 try { bilSheetService.syncUser(bilWebseviceLog, userId, optType); }catch (Exception e ...

  9. java8 异步api、循环、日期

    java8 异步api.循环.日期 转载请注明出处:https://www.cnblogs.com/funnyzpc/p/10801470.html 异步api 对于多任务耗时的业务场景,一般我们会用 ...

  10. Programming In Lua 第八章

    1, 也就是说,lua虽然会把代码预编译成中间码,以提高运行速度.但其会在程序运行过程中需要编译器,所以其仍然是解释型语言.loadfile会加载一个文件并将其编译成中间码,并返回一个函数. 2, 3 ...