手写MyBatis代码生成器Maven插件

chatgpt/2023/9/26 14:34:26

代码链接:codegen-maven-plugin

在使用MyBatis时,需要根据库表结构编写一些通用的Mapper interface、XML、Entity,这些重复操作可以通过代码生成器自动生成,大大提高开发效率。
目前,代码生成分为两种方式:

  • 模版引擎:如 velocity
  • 代码直接生成:如 javapoet

本文使用 javapoet直接生成Java代码,使用jdom2生成XML文件。

Maven 插件

自定义Maven插件
可参考Plugin Developers Centre

Maven内置以下3个生命周期,每个生命周期(Lifecycle)有一个或多个阶段(Phase),每个阶段可以注册多个Plugin。

  • default : handles your project deployment
  • clean : handles project cleaning
  • site : handles the creation of your project’s web site

其中,default生成周期常用,包含以下阶段,按顺序执行:

  1. validate - validate the project is correct and all necessary information is available
  2. compile - compile the source code of the project
  3. test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  4. package - take the compiled code and package it in its distributable format, such as a JAR.
  5. verify - run any checks on results of integration tests to ensure quality criteria are met
  6. install - install the package into the local repository, for use as a dependency in other projects locally
  7. deploy - done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.

如果单独执行某个Phase,会执行改Phase之前所有的Phases。

自定义插件套路如下:

// 选定默认Phase,可在<build>中覆盖
@Mojo(name = "codegen", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class SQLTableGenMojo extends AbstractMojo {@Parameter(defaultValue = "${project}", required = true, readonly = true)private MavenProject project;@Parameter(property = "skip", defaultValue = "false")private boolean skip;// 自定义xml项@Parameter(property = "absoluteFilePath", required = true, readonly = true)private String absoluteFilePath;@Overridepublic void execute() throws MojoExecutionException, MojoFailureException {if (skip) {getLog().info("codegen is skipped!");return;}if (StringUtils.isBlank(absoluteFilePath) || !Files.exists(Paths.get(absoluteFilePath))) {// 异常throw new MojoExecutionException("Failed to generate code: config file does not exist");}// 日志通过getLog()获取getLog().info("codegen-maven-plugin for " + project.getName() + " starting!");doExecute(project.getBasedir().getAbsolutePath(),absoluteFilePath);}public void doExecute(String baseAbsoluteDir,String filePath) throws MojoExecutionException {// ...}}

javapoet生成Java源代码

javapoet通过Fluent api的方式构建代码:

        ClassName criterion = ClassName.get(configProperties.getMapperInterfaceGenPkg(),"Criterion");TypeSpec criterion = TypeSpec.classBuilder("Criterion")// 加annotation(也可以使用AnnotationSpec构建).addAnnotation(Data.class)// List生成方式使用ParameterizedTypeName// private List<Criterion> criteria  .addField(FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(List.class),criterion),"criteria",Modifier.PRIVATE).build())// private Object value;.addField(FieldSpec.builder(Object.class, "value", Modifier.PRIVATE).build())// private boolean noValue;.addField(FieldSpec.builder(TypeName.BOOLEAN, "noValue", Modifier.PRIVATE).build())// 添加构造器.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(String.class, "condition").build()).addParameter(ParameterSpec.builder(Object.class, "value").build())// addStatement最后不加分号.addStatement("System.out.println(123);\n this(condition, value, null)").build())// private void addCriterion(String property){...}.addMethod(MethodSpec.methodBuilder("addCriterion").addModifiers(Modifier.PRIVATE).returns(TypeName.VOID).addParameter(String.class,"property")// $T表示类型占位符// $L for Literals// $S for Strings// $T for Types// $N for Names.addStatement("    if (value == null) {\n"+ "    throw new $T(\"Value for condition cannot be null \");\n"+ "}\n"+ "criteria.add(new $T(condition,value));",RuntimeException.class,criterion).build())).build();

JDom2生成XML

Document xml = new Document();DocType mybatisDocType = new DocType("mapper", "-//mybatis.org//DTD Mapper 3.0//EN","http://mybatis.org/dtd/mybatis-3-mapper.dtd");xml.setDocType(mybatisDocType);Comment comment = new Comment("Auto generated by codegen-maven-plugin @author:baotingyu " + LocalDateTime.now());xml.addContent(comment);Element mapper = new Element("mapper");// <mapper namespace="xxx">mapper.setAttribute("namespace", configProperties.getMapperInterfaceGenPkg()+"."+xmlName);xml.addContent(mapper);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.exyb.cn/news/show-5314373.html

如若内容造成侵权/违法违规/事实不符,请联系郑州代理记账网进行投诉反馈,一经查实,立即删除!

相关文章

【flutter】flutter如何让app内字体大小不随着系统改变而改变

如果我们不特意设置&#xff0c;flutter开发的app他的字体大小是会跟着系统设置的字体大小而改变&#xff0c;这样就会导致页面出现布局错乱问题&#xff0c;那么如何解决这个问题呢&#xff1f;我也搜索了相关资料&#xff0c;有两个常用也是网络上搜集到比较多的方法&#xf…

中国计算机学会推荐国际学术期刊(网络与信息安全)

序号刊物简称刊物全称分类类型专业领域1TDSCIEEE Transactions on Dependable and Secure ComputingA期刊网络与信息安全2TIFSIEEE Transactions on Information Forensics and SecurityA期刊网络与信息安全3Journal of CryptologyA期刊网络与信息安全1TISSECACM Transactions …

通过SSH实现将本地端口反向代理到公网服务器

使用场景 有一台公网服务器&#xff0c;能够对外开放服务进行访问&#xff0c;但是这个公网服务器资源较低&#xff0c;无法运行太多服务 有一台闲置电脑可以全天候开机使用&#xff0c;且配置较好&#xff0c;可以部署多个服务&#xff0c;但是没有公网IP 需求&#xff1a;将…

时序预测 | Python实现NARX-DNN空气质量预测

时序预测 | Python实现NARX-DNN空气质量预测 目录 时序预测 | Python实现NARX-DNN空气质量预测效果一览基本介绍研究内容程序设计参考资料效果一览 基本介绍 时序预测 | Python实现NARX-DNN空气质量预测 研究内容 Python实现NARX-DNN空气质量预测,使用深度神经网络对比利时空气…

最新多模态3D目标检测论文汇总(PDF+代码)

目前在自动驾驶领域&#xff0c;多模态3D目标检测是一个非常重要的研究热点。由于引入了其他传感器数据&#xff0c;多模态3D目标检测在性能上明显优于纯视觉的方案&#xff0c;可以同时预测周围物体的类别、位置和大小&#xff0c;因此对于自动驾驶领域的同学来说&#xff0c;…

ifcfg-ens33中的ONBOOT字段是什么作用?

在CentOS或其他基于Red Hat Enterprise Linux (RHEL)的Linux发行版中&#xff0c;ifcfg-ens33是网络配置文件&#xff0c;用于配置网卡设备ens33的网络参数。ifcfg-ens33文件位于/etc/sysconfig/network-scripts/目录下&#xff08;可能因系统版本而略有不同&#xff0c;例如/e…

overflow的默认值visible

1.修改前的代码 html代码&#xff1a; <div class"main"><div class"test">111111</div><div class"test">111111111</div><div class"test">111111111</div><div class"test&qu…

学习记录——Octave Convolution、LSK

Octave Convolution 2019 ICCV 自然世界中的图像存在高低频&#xff0c;卷积层的输出特征图以及输入通道&#xff0c;也都存在高、低频分量。 低频分量支撑的是整体轮廓&#xff0c;高频分量则关注细节&#xff0c;显然&#xff0c;低频分量是存在冗余的&#xff0c;在编码过程…
推荐文章