mybatis generator插件系列--lombok插件 (减少百分之九十bean代码)
经常使用mybatis generator生成代码的你
有没有因为生成的getter/setter而烦恼呢?
有没有生成后又手动加toString/hashCode/Equals方法呢?
有没有改一个字段又要手动改写getter/setter/toString/hashCode/Equals呢?
下面我将介绍一个mybatis generator Lombok插件来解决以上所有问题
Lombok是一款简单强大的代码工具,没使用过Lombok插件的同学可以用10分钟了解下
1、首先定义Lombok插件
LombokPlugin.java
package com.demo.mybatis.plugin;
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.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 java.util.*;
/**
* A MyBatis Generator plugin to use Lombok's annotations.
* For example, use @Data annotation instead of getter ands setter.
*
* @author Paolo Predonzani (http://softwareloop.com/)
*/
public class LombokPlugin extends PluginAdapter {
private final Collection<Annotations> annotations;
/**
* LombokPlugin constructor
*/
public LombokPlugin() {
annotations = new LinkedHashSet<Annotations>(Annotations.values().length);
}
/**
* @param warnings list of warnings
* @return always true
*/
public boolean validate(List<String> warnings) {
return true;
}
/**
* Intercepts base record class generation
*
* @param topLevelClass the generated base record class
* @param introspectedTable The class containing information about the table as
* introspected from the database
* @return always true
*/
@Override
public boolean modelBaseRecordClassGenerated(
TopLevelClass topLevelClass,
IntrospectedTable introspectedTable
) {
addAnnotations(topLevelClass);
return true;
}
/**
* Intercepts primary key class generation
*
* @param topLevelClass the generated primary key class
* @param introspectedTable The class containing information about the table as
* introspected from the database
* @return always true
*/
@Override
public boolean modelPrimaryKeyClassGenerated(
TopLevelClass topLevelClass,
IntrospectedTable introspectedTable
) {
addAnnotations(topLevelClass);
return true;
}
/**
* Intercepts "record with blob" class generation
*
* @param topLevelClass the generated record with BLOBs class
* @param introspectedTable The class containing information about the table as
* introspected from the database
* @return always true
*/
@Override
public boolean modelRecordWithBLOBsClassGenerated(
TopLevelClass topLevelClass,
IntrospectedTable introspectedTable
) {
addAnnotations(topLevelClass);
return true;
}
/**
* Prevents all getters from being generated.
* See SimpleModelGenerator
*
* @param method the getter, or accessor, method generated for the specified
* column
* @param topLevelClass the partially implemented model class
* @param introspectedColumn The class containing information about the column related
* to this field as introspected from the database
* @param introspectedTable The class containing information about the table as
* introspected from the database
* @param modelClassType the type of class that the field is generated for
*/
@Override
public boolean modelGetterMethodGenerated(
Method method,
TopLevelClass topLevelClass,
IntrospectedColumn introspectedColumn,
IntrospectedTable introspectedTable,
ModelClassType modelClassType
) {
return false;
}
/**
* Prevents all setters from being generated
* See SimpleModelGenerator
*
* @param method the setter, or mutator, method generated for the specified
* column
* @param topLevelClass the partially implemented model class
* @param introspectedColumn The class containing information about the column related
* to this field as introspected from the database
* @param introspectedTable The class containing information about the table as
* introspected from the database
* @param modelClassType the type of class that the field is generated for
* @return always false
*/
@Override
public boolean modelSetterMethodGenerated(
Method method,
TopLevelClass topLevelClass,
IntrospectedColumn introspectedColumn,
IntrospectedTable introspectedTable,
ModelClassType modelClassType
) {
return false;
}
/**
* Adds the lombok annotations' imports and annotations to the class
*
* @param topLevelClass the partially implemented model class
*/
private void addAnnotations(TopLevelClass topLevelClass) {
for (Annotations annotation : annotations) {
topLevelClass.addImportedType(annotation.javaType);
topLevelClass.addAnnotation(annotation.asAnnotation());
}
}
@Override
public void setProperties(Properties properties) {
super.setProperties(properties);
//@Data is default annotation
annotations.add(Annotations.DATA);
for (String annotationName : properties.stringPropertyNames()) {
if (annotationName.contains(".")) {
// Not an annotation name
continue;
}
String value = properties.getProperty(annotationName);
if (!Boolean.parseBoolean(value)) {
// The annotation is disabled, skip it
continue;
}
Annotations annotation = Annotations.getValueOf(annotationName);
if (annotation == null) {
continue;
}
String optionsPrefix = annotationName + ".";
for (String propertyName : properties.stringPropertyNames()) {
if (!propertyName.startsWith(optionsPrefix)) {
// A property not related to this annotation
continue;
}
String propertyValue = properties.getProperty(propertyName);
annotation.appendOptions(propertyName, propertyValue);
annotations.add(annotation);
annotations.addAll(Annotations.getDependencies(annotation));
}
}
}
@Override
public boolean clientGenerated(
Interface interfaze,
TopLevelClass topLevelClass,
IntrospectedTable introspectedTable
) {
interfaze.addImportedType(new FullyQualifiedJavaType(
"org.apache.ibatis.annotations.Mapper"));
interfaze.addAnnotation("@Mapper");
return true;
}
private enum Annotations {
DATA("data", "@Data", "lombok.Data"),
BUILDER("builder", "@Builder", "lombok.Builder"),
ALL_ARGS_CONSTRUCTOR("allArgsConstructor", "@AllArgsConstructor", "lombok.AllArgsConstructor"),
NO_ARGS_CONSTRUCTOR("noArgsConstructor", "@NoArgsConstructor", "lombok.NoArgsConstructor"),
ACCESSORS("accessors", "@Accessors", "lombok.experimental.Accessors"),
TO_STRING("toString", "@ToString", "lombok.ToString");
private final String paramName;
private final String name;
private final FullyQualifiedJavaType javaType;
private final List<String> options;
Annotations(String paramName, String name, String className) {
this.paramName = paramName;
this.name = name;
this.javaType = new FullyQualifiedJavaType(className);
this.options = new ArrayList<String>();
}
private static Annotations getValueOf(String paramName) {
for (Annotations annotation : Annotations.values())
if (String.CASE_INSENSITIVE_ORDER.compare(paramName, annotation.paramName) == 0)
return annotation;
return null;
}
private static Collection<Annotations> getDependencies(Annotations annotation) {
if (annotation == ALL_ARGS_CONSTRUCTOR)
return Collections.singleton(NO_ARGS_CONSTRUCTOR);
else
return Collections.emptyList();
}
// A trivial quoting.
// Because Lombok annotation options type is almost String or boolean.
private static String quote(String value) {
if (Boolean.TRUE.toString().equals(value) || Boolean.FALSE.toString().equals(value))
// case of boolean, not passed as an array.
return value;
return value.replaceAll("[\\w]+", "\"$0\"");
}
private void appendOptions(String key, String value) {
String keyPart = key.substring(key.indexOf(".") + 1);
String valuePart = value.contains(",") ? String.format("{%s}", value) : value;
this.options.add(String.format("%s=%s", keyPart, quote(valuePart)));
}
private String asAnnotation() {
if (options.isEmpty()) {
return name;
}
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append("(");
boolean first = true;
for (String option : options) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(option);
}
sb.append(")");
return sb.toString();
}
}
}
2、然后为mybatisgenerator配置插件
<?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="context1">
<!-- 使用自带序列化插件 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- 使用自定义的插件 -->
<plugin type="com.demo.mybatis.plugin.LombokPlugin"/>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8"
userId="root" password="123456">
</jdbcConnection>
<javaModelGenerator targetPackage="com.ilovey.biz.entity.base"
targetProject="ilovey.biz/src/main/java"/>
<sqlMapGenerator targetPackage="com.ilovey.biz.mapper.base"
targetProject="ilovey.biz/src/main/resources"/>
<javaClientGenerator targetPackage="com.ilovey.biz.mapper.base"
targetProject="ilovey.biz/src/main/java" type="XMLMAPPER"/>
<table tableName="us_user_info" domainObjectName="UsUserInfo">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
3、生成效果
package com.demo.biz.entity.base;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class UsUserInfo implements Serializable {
/**
*
*/
private Integer id;
/**
* 用户id
*/
private Integer userId;
/**
* 昵称
*/
private String nickName;
/**
* 头像
*/
private String headImage;
/**
* 手机号码
*/
private String mobile;
/**
* 性别(0保密,1男,2女)
*/
private Integer sex;
/**
* 地区
*/
private Integer region;
/**
* 个性签名
*/
private String signature;
/**
* 用户类型(1普通用户,2达人用户)
*/
private Byte type;
/**
* 用户种类
*/
private String kindCode;
/**
* r热度
*/
private Integer hot;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
private static final long serialVersionUID = 1L;
}
本文所有代码及demo:https://gitee.com/chaocloud/generator-demo.git
mybatis generator插件系列--lombok插件 (减少百分之九十bean代码)的更多相关文章
- Eclipse MyBatis generator 1.3.7插件的核心包(中文注释)
一.最近刚搭建一个项目框架,使用springboot + mybatis,但是在使用Eclipse开发时发现开发mybatis的Dao.mapper.xml和entity时特别不方便,手工去写肯定是不 ...
- mybatis generator插件系列--分页插件
1.首先定义分页插件 MysqlPagePlugin.java package com.demo.mybatis.plugin; import org.mybatis.generator.api.Co ...
- MyBatis Generator实现MySQL分页插件
MyBatis Generator是一个非常方便的代码生成工具,它能够根据表结构生成CRUD代码,可以满足大部分需求.但是唯一让人不爽的是,生成的代码中的数据库查询没有分页功能.本文介绍如何让MyBa ...
- IDEA自用插件,驼峰插件,MyBatis插件,Lombok插件
IDEA自用插件 驼峰插件:CamelCase,Shift + Alt + u快速切换驼峰 MyBatisX插件:快速在mapper之间跳转 Lombok插件:注解实现get.set方法 MyBati ...
- Mybatis generator 数据库反向生成插件的使用
直接上干货: 可生成数据库表对应的po mpper接口文件 mapper.xml文件.文件中自动配置了部分常用的dao层方法.用于快速快发. 1.pom中引入插件: <plugin> & ...
- MyBatis Generator作为maven插件自动生成增删改查代码及配置文件例子
什么是MyBatis Generator MyBatis Generator (MBG) 是一个Mybatis的代码生成器,可以自动生成一些简单的CRUD(插入,查询,更新,删除)操作代码,model ...
- maven web项目下mybatis generator的使用
idea中新建maven web项目,完善java,resources目录: pom.xml中添加jdbc依赖,mybatis generator的依赖和插件: <dependencies> ...
- mybatis generator 生成带中文注释的model类
将org.mybatis.generator.interal.DefaultCommentGenerator类的addFieldComment方法重写,代码如下: public void addFie ...
- Springboot 系列(十二)使用 Mybatis 集成 pagehelper 分页插件和 mapper 插件
前言 在 Springboot 系列文章第十一篇里(使用 Mybatis(自动生成插件) 访问数据库),实验了 Springboot 结合 Mybatis 以及 Mybatis-generator 生 ...
随机推荐
- [javascript]编码&i字符串格式化&nput历史记录&清空模态框
js中编码问题 https://www.haorooms.com/post/js_escape_encodeURIComponent 我在前端js添加时候创建dom时候,有汉字,发现是乱码就研究了下 ...
- 2.keras实现-->字符级或单词级的one-hot编码 VS 词嵌入
1. one-hot编码 # 字符集的one-hot编码 import string samples = ['zzh is a pig','he loves himself very much','p ...
- javascript console自动点击页面元素
原文地址https://jingyan.baidu.com/article/0a52e3f41c0b0abf63ed726d.html 这里拿百度音乐VIP兑换页面来做演示. 首先打开百度音乐VIP兑 ...
- 问题排查之'org.apache.rocketmq.spring.starter.core.RocketMQTemplate' that could not be found.- Bean method 'rocketMQTemplate' in 'RocketMQAutoConfiguration' not loaded.
背景 今天将一个SpringBoot项目的配置参数从原有的.yml文件迁移到Apollo后,启动报错“Bean method 'rocketMQTemplate' in 'RocketMQAutoCo ...
- 20155333 2016-2017-2 《Java程序设计》第九周学习总结
20155333 2016-2017-2 <Java程序设计>第九周学习总结 教材学习内容总结 JDBC(Java DataBase Connectivity) 驱动的四种类型 JDBC- ...
- Zookeeper使用实例——服务节点管理
分布式处理中,总会存在多个服务节点同时工作,并且节点数量会随着网络规模的变化而动态增减,服务节点也有可能发生宕机与恢复.面对着动态增减的服务节点,我们如何保证客户请求被服务器正确处理呢.我们可以通过z ...
- Hive表中Partition的创建
作用: 在Hive Select查询中一般会扫描整个表内容,会消耗很多时间做没必要的工作.有时候只需要扫描表中关心的一部分数据,在对应的partition里面去查找就可以,减少查询时间. 1. 创建表 ...
- linux复制指定目录下的全部文件到另一个目录中,linux cp 文件夹
linux复制指定目录下的全部文件到另一个目录中复制指定目录下的全部文件到另一个目录中文件及目录的复制是经常要用到的.linux下进行复制的命令为cp.假设复制源目录 为 dir1 ,目标目录为dir ...
- python条件判断if···else、循环while和for
1.if···else条件判断基本语法 if 条件: 执行语句 elif 条件 : 执行语句 …… else : 执行语句 var=input("请输入表示会员级别的数字(1-5):&quo ...
- web应用下的安全问题以及tomcat/nginx对应解决方法(持续更新、亲测可解决问题)
最近一券商那边扫描反馈了下面几个非业务型安全漏洞,要求解决,如下: XSS 自己写个脚本response的时候对特殊字符进行了处理,或者网上搜下一堆(不要忘了回车.换行). HTML form wit ...