SqlToJava小工具【version 2.0】

前言

本篇文章是对之前开发的 SqlToJava小工具 的优化。为什么要优化?肯定是要将偷懒的爱好进行到底~之前制作的 SqlToJava小工具 仅针对单机架构下的 SpringBoot 项目实体类的生成,由于后期接触了实际开发项目,需要用到 swagger 自动生成接口文档,方便前后端联调,那么,就需要在实体类中添加生成 swagger 内容的注解,还是由于一个个手动输入太麻烦,所以有了现在的优化版 SqlToJava小工具。同时,由于创建人、创建日期、更新人、更新日期、租户ID、租户名称都是设置好的可以自动填充的字段,所以,本次优化也对这些字段进行了 “特殊处理”(说的很高深的样子,其实就是添加自动填充注解,哈哈)。

之前的结果示例:

    /**
	* 主键
	*/
	@TableId(value = "id", type = IdType.ASSIGN_ID)
	private Long id;
	/**
	* 创建人
	*/
	@TableField("create_user")
	private Long createUser;
	/**
	* 创建人名称
	*/
	@TableField("create_user_name")
	private String createUserName;
	/**
	* 创建日期
	*/
	@TableField("create_time")
	private Date createTime;
	/**
	* 修改人
	*/
	@TableField("update_user")
	private Long updateUser;
	/**
	* 修改日期
	*/
	@TableField("update_time")
	private Date updateTime;
	@TableLogic
	/**
	* 租户ID
	*/
	@TableField("tenant_id")
	private String tenantId;

优化的结果示例:

    /**
	* 主键
	*/
	@ApiModelProperty(value = "主键")
	@TableId(value = "id", type = IdType.ASSIGN_ID)
	private Long id;
    /**
	 * 创建人
	 */
	@ApiModelProperty(value = "创建人")
	@TableField(value = "create_user", fill = FieldFill.INSERT)
	private Long createUser;
	/**
	 * 创建人姓名
	 */
	@ApiModelProperty(value = "创建人姓名")
	@TableField(value = "create_user_name", fill = FieldFill.INSERT)
	private String createUserName;
	/**
	 * 创建日期
	 */
	@ApiModelProperty(value = "创建日期")
	@TableField(value = "create_time", fill = FieldFill.INSERT)
	private Date createTime;
	/**
	 * 修改人
	 */
	@ApiModelProperty(value = "修改人")
	@TableField(value = "update_user", fill = FieldFill.INSERT_UPDATE)
	private Long updateUser;
	/**
	 * 修改日期
	 */
	@ApiModelProperty(value = "修改日期")
	@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
	private Date updateTime;
	/**
	 * 租户ID
	 */
	@ApiModelProperty(value = "租户ID")
	@TableField(value = "tenant_id", fill = FieldFill.INSERT)
	private String tenantId;

开始操作:

来直接看代码吧:

# -*- coding: utf-8 -*-
"""
Created on Mon Sep 05 21:24:42 2022

@author: angell
"""
from tkinter import *
from tkinter import messagebox

TYPE_DICT = {'int': 'Integer', 'varchar': 'String', 'char': 'String', 'nchar': 'String',\
             'nvarchar': 'String', 'text': 'String', 'ntext': 'String', 'tinyint': 'Integer',\
             'smallint': 'Integer', 'bit': 'Boolean', 'bigint': 'Long', 'float': 'Double',\
             'decimal': 'BigDecimal', 'money': 'BigDecimal', 'smallmoney': 'BigDecimal',\
             'numeric': 'BigDecimal', 'real': 'Float', 'uniqueidentifier': 'String',\
             'smalldatetime': 'Timestamp', 'datetime': 'Date', 'timestamp': 'byte[]', 'binary': 'byte[]',\
             'varbinary': 'byte[]', 'image': 'byte[]', 'sql_variant': 'String', 'double':'Double'}
    
def process(context):
    lines = context.strip().split("\n")
    res = ''
    for i in range(len(lines)):
        if i == 1:
            continue
        line = lines[i].strip().split(' ')
        while '' in line:
            line.remove('')
        field = line[0].strip('`')
        kind = TYPE_DICT[line[1].split('(')[0]]
    
        spl = line[0].strip('`').split('_')
        for j in range(len(spl)):
            if j == 0:
                variable = spl[0]
            else:
                variable += spl[j][0].upper() + spl[j][1:]
             
        comment = lines[i].strip().split('comment')[1].replace('\'','').replace(',','').strip()
        if i == 0:
            res += f'\n\t/**\n\t* {comment}\n\t*/\n\t@ApiModelProperty(value = "{comment}")\n\t@TableId(value = "{field}", type = IdType.ASSIGN_ID)\n\tprivate {kind} {variable};'
        elif variable == 'isDeleted':
            res += f'\n\t/**\n\t* {comment}\n\t*/\n\t@ApiModelProperty(value = "{comment}")\n\t@TableField("{field}")\n\t@TableLogic\n\tprivate {kind} {variable};'
        elif variable in ['createUser', 'createUserName', 'createTime', 'tenantId', 'tenantName']:
            res += f'\n\t/**\n\t* {comment}\n\t*/\n\t@ApiModelProperty(value = "{comment}")\n\t@TableField(value = "{field}", fill = FieldFill.INSERT)\n\tprivate {kind} {variable};'
        elif variable in ['updateUser', 'updateTime']:
            res += f'\n\t/**\n\t* {comment}\n\t*/\n\t@ApiModelProperty(value = "{comment}")\n\t@TableField(value = "{field}", fill = FieldFill.INSERT_UPDATE)\n\tprivate {kind} {variable};'
        else:
            res += f'\n\t/**\n\t* {comment}\n\t*/\n\t@ApiModelProperty(value = "{comment}")\n\t@TableField("{field}")\n\tprivate {kind} {variable};'
    return res

root = Tk()
root.title("SqlToJava小工具 v2.0")
root.resizable(0,0)
root.configure(bg="#bbb")
root.geometry('1100x610')                 

l1 = Label(root, text="Sql:", background="#bbb", font=('宋体', '12')).place(x=50, y=25)
input_text = Text(root, bg="#eee", font=('宋体', '12'))
input_text.pack() # 实例化文本框,否则对文本框内容get、delete、insert时会报'NoneType'
input_text.place(x=50, y=70, width=450, height=450)

l2 = Label(root, text="Result:", background="#bbb", font=('宋体', '12')).place(x=590, y=20)
result_text = Text(root, bg="#eee", font=('宋体', '12'))
result_text.pack()
result_text.place(x=590, y=65, width=450, height=500)

def on_click_clean():
    input_text.delete(1.0,END)
    
def on_click_output():
    context = input_text.get('0.1','end')
    try:
        result = process(context)
        result_text.delete(1.0,END)
        result_text.insert(END,result)
    except:
        string ='未发现数据或数据格式有误!请检查输入!              '
        messagebox.showinfo(title='提示', message = string)
        
button_clean = Button(root, text="Clean", bg="#7AD4F1", font=('Arail', '10'), command = on_click_clean)
button_clean.place(x=305, y=550, width=60, height=25)
button_change = Button(root, text="Change", bg="yellow", font=('Arail', '10'), command = on_click_output)
button_change.place(x=380, y=550, width=100, height=25)

root.mainloop()

复制代码,保存到一个 .py 结尾的文件中,再运行就可以获得优化版的 SqlToJava小工具了。有图有真相:

后记

和上一版本比较,【SqlToJava小工具 version 2.0 】仅在 process 函数中增加了对 variable 值的判断条件,想了解更多代码细节以及打包成 .exe 程序,参考上一版本博客:SqlToJava小工具 | MySQL 语句转换成 Java 代码,自动生成注解和注释、转驼峰命名,快速得到 SpringBoot 实体类 Entity(二)

想具体了解前因(为什么开发这个偷懒工具),请查看文章:Spring Boot 实体类 Entity的自动生成,利用Python实现 sql 语句快速转换成 Java 代码(一)

【原创不易,点个赞吧】



 

猜你喜欢

转载自blog.csdn.net/weixin_47068543/article/details/126714106