很多时候,我们需要对某个表进行业务开发,生成对应的controller,service,dao,entity等操作类,分别编写增、删、改、查业务操作方法 ,而这些细活往往比较简单且没有挑战性,纯粹苦力活,又累又耗时,程序的生命是有限,不能浪费,这些方法完全可以有迹可寻的可以采用某些方法快速产生,因此想到python这个利器,采用 flask服务基于html定制代码模板,于是有了代码生成器的开发,目前有部份功能还未完成,不过还是可以满足基本的开发应用;

先说明,首先文中所用到的模板,是基于我们现在有项目定制的,像其中的BaseMarketMongoServiceImpl等类是我们框架底层的基类,如果你需要使用请自行到templates目录更改;

开发工具版本:python 3.5 + flask + pycharm

上代码:

# -*- coding: UTF-8 -*-
'''
Created on 2018年7月24日
通过模板自动生成java文件,可生成controller,service,dao,entity层等类,提供简单的list,findById,delete,save,update,page方法
@author: JL
'''

import os
import json
import time
import tarfile
from flask import Flask, render_template, send_from_directory, request

app = Flask(__name__)


@app.route('/index')
def index():
    return render_template('create_class.html')


@app.route("/download/<filename>", methods=['GET'])
def downloader(filename):
    # 指定文件下载目录,默认为当前项目根路径
    dirpath = os.path.join(app.root_path, '')
    # as_attachment=True 表示下载
    return send_from_directory(dirpath, filename, as_attachment=True)


@app.route('/createClass', methods=['GET', 'POST'])
def create_class():
    file_name = msg = None
    # {'column': {'age': 'int', 'id': 'String', 'address': 'String', 'name': 'String'}, 'table': 'cc_user'}
    fields = request.form['fields']
    if len(fields) <= 0:
        msg='request data json is null!'
    print(fields)
    j = json.loads(fields, encoding='utf-8')
    class_name = j['class']
    package = j['package']
    db_type = j['type']
    if len(class_name) <= 0 :
        msg = 'className is null!'
    if len(package) <= 0:
        msg = 'package is null'
    if len(db_type) <= 0:
        msg = 'type is null'
    print(class_name + '\n' + package)
    if not msg or len(msg) <= 0:
        d = time.strftime("%Y-%m-%d", time.localtime())
        entity = request.form.get('entity')
        if entity and len(entity) >= 1:
            print('--- create entity class')
            create_entity(class_name, package, j['table'], j['column'], db_type, d)
        dao = request.form.get('dao')
        if dao and len(dao) >= 1:
            print('--- create dao class')
            create_dao(class_name, package, d)
        service = request.form.get('service')
        if service and len(service) >= 1:
            print('--- create service class')
            create_service(class_name, package, d)
        controller = request.form.get('controller')
        if controller and len(controller) >= 1:
            print('--- create controller class')
            create_controller(class_name, package, d)
            file_name = make_targz()
    return render_template('create_class.html', msg=msg, file_name=file_name)


# 创建entity
def create_entity(class_name, package, table_name, columns, db_type, date):
    propertys = ''
    methods = ''
    if columns:
        for key in columns.keys():
            propertys += 'private %s %s;' % (columns[key], key) + '\n'
            p1 = 'public void get%s() {\nreturn this.%s;\n}' % (key.title(), key)
            p2 = 'public %s set%s(%s %s) {\nthis.%s = %s;\n}' % (columns[key], key.title(), columns[key], key, key, key)
            methods += p1+'\n'+p2
    c = {'package': package + '.entity',
         'entity_package': package + '.entity.' + class_name,
         'class_name': class_name,
         'table_name': table_name,
         'propertys': propertys,
         'methods': methods,
         'date': date}
    if db_type == 'mongodb':
        s = render_template('entity_mongodb_templates.html', **c)
        create_java_file(class_name, package + '.entity', s)
    elif db_type == 'mysql':
        s = render_template('entity_mysql_templates.html', **c)
        create_java_file(class_name, package + '.entity', s)
        s = render_template('entity_mysql_mapper_templates.html', **c)
        create_java_file(class_name, package + '.entity', s, 'Mapper.xml')


# 创建Dao
def create_dao(class_name, package, date):
    c = {'package': package + '.dao',
         'class_name': class_name,
         'entity_package': package + '.entity.' + class_name,
         'date': date}
    s = render_template('dao_templates.html', **c)
    create_java_file(class_name + 'Dao', package + '.dao', s)


# 创建Service
def create_service(class_name, package, date):
    c = {'package': package + '.service',
         'class_name': class_name,
         'small_class_name': small_str(class_name),
         'entity_package': package + '.entity.' + class_name,
         'dao_package': package + '.dao.' + class_name + 'Dao',
         'date': date}
    s = render_template('service_templates.html', **c)
    create_java_file(class_name + 'Service', package + '.service', s)


# 创建controller
def create_controller(class_name, package, date):
    c = {'package': package + '.entity',
         'class_name': class_name,
         'small_class_name': small_str(class_name),
         'entity_package': package + '.entity.' + class_name,
         'dao_package': package + '.dao.' + class_name + 'Dao',
         'service_package': package + '.dao.' + class_name + 'Service',
         'date': date}
    s = render_template('controller_templates.html', **c)
    # print(s)
    create_java_file(class_name + 'Controller', package + '.controller', s)


# 将首字母转换为小写
def small_str(s):
    if len(s) <= 1:
        return s
    return (s[0:1]).lower() + s[1:]


# 创建java文件
def create_java_file(class_name, package, text, suffix='.java'):
    dirs = 'D:/temp/python/'+package.replace('.', '/')+'/'
    if not os.path.exists(dirs):
        os.makedirs(dirs, 0o777)
    fd = os.open(dirs + class_name + suffix, os.O_WRONLY | os.O_CREAT)
    os.write(fd, text.encode(encoding="utf-8", errors="strict"))
    os.close(fd)


#生成tar.gz压缩包
def make_targz():
    file_name = 'com.tar.gz'
    source_dir = 'D:/temp/python/'
    with tarfile.open(file_name, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))
    return file_name


if __name__ == '__main__':
    app.run()

模板定制:java结构代码

package {{ package }};

import org.springframework.data.mongodb.core.mapping.Document;

/**
 * @author admin
 * @version 1.0
 * @Description 实体类
 * @date {{ date }}
 */
@Document(collection = "{{ table_name }}")
public class {{ class_name }} {

{{ propertys }}

{{ methods }}
}

其它就不一一贴上代码,文末会贴上项目下载码云链接;

运行服务,在浏览器中输入:http://127.0.0.1:5000/index

输入数据结构json串,选择生成的类,结构比较简单,都看的懂,提交后,页脚有下载打包的链接;

用100多行python代码开发java代码生成器-LMLPHP

下载解压即有了java代码

用100多行python代码开发java代码生成器-LMLPHP

打开目录下java文件

用100多行python代码开发java代码生成器-LMLPHP

完毕,当然功能比较简单,后续再完善。

最后贴上码云中项目的地址:https://gitee.com/omsgit/auto-create-java

05-05 11:31