python能做的100件事02-代码生成器

简介

代码主要用于生成java web mvc开发需要的entity,dao,service,controller层文件以及公用的mapper文件,基于数据库表结构生成,基于mysql数据库,需要用到的第三方库主要是python连接mysql的库pymysql。通过pip install pymysql命令安装即可。如有不合适的地方请拷贝代码自行修改或定制功能。以下是生成的目录和文件预览,完整代码见文末,如果拷贝代码不方便,可以到此处仓库拷贝代码:

https://gitee.com/lxx-new/python-creater/blob/master/create3.py

示例数据表代码

CREATE TABLE `pms_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `name` varchar(64) NOT NULL COMMENT '用户名',
  `full_name` varchar(64) NOT NULL COMMENT '姓名',
  `phone_number` varchar(64) NOT NULL COMMENT '电话',
  `email` varchar(64) NOT NULL COMMENT '邮箱',
  `c_time` timestamp NOT NULL DEFAULT current_timestamp() COMMENT '创建时间',
  `u_time` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='用户表'

python能做的100件事02-代码生成器_第1张图片
python能做的100件事02-代码生成器_第2张图片
python能做的100件事02-代码生成器_第3张图片python能做的100件事02-代码生成器_第4张图片python能做的100件事02-代码生成器_第5张图片

完整代码

#coding=utf-8

import pymysql
import os
import json
import time
from string import Template
import codecs
import sys

#reload(sys)
#sys.setdefaultencoding('utf-8')


basePath = "/home/eva/文档/create/"#生成文件保存路径
host = "127.0.0.1" #mysql所在机子IP
port = 3306 #mysql端口
uname = "root" #mysql数据库用户名
upwd="123456" #mysql数据库密码
dbName = "mall_pms" #mysql数据库名称
prefix = "pms_" #表名前缀,生成实体类时是否去掉表前缀,如果不需要就设置为空字符。
packageUrl = "com.lee.mall.pms" #包路径,生成的文件中package的值
entityPackage = "" #实体类的包名,默认entity
daoPackage = "" #dao文件包名,默认dao
servicePackage = "" #service文件包名,默认service
controllerPackage = "" #controller文件包名,默认controller
moduleName = "" #模块名,即Controller类注解@RequestMapping("/moduleName")的值,如不需要,留空即可。

#数据库链接
def getConn():
    conn = pymysql.connect(host=host,port=port,user=uname,passwd=upwd,db=dbName,charset='utf8')
    return conn

#数据库游标
def getCur(conn):
    cur = conn.cursor()
    return cur

#数据表集合
def getTablesDic():
    sql = "show tables;"
    conn = getConn()
    cur = getCur(conn)
    count = cur.execute(sql)
    tables = cur.fetchall()
    return tables

#获取类名
def getClassName(tableName):
    #去掉表前缀
    tableName = tableName.replace(prefix,"")
    className = ""
    if tableName.find("_") >= 0:
        subs = tableName.split("_")
        for sub in subs:
            className = className + sub.lower().capitalize()
    else:
        className = tableName.lower().capitalize()
    return className
        
#查询数据库字段,字段类型,字段注释
def getTableColumns(dbName,tableName):
    sql = "select column_name,data_type,column_comment from information_schema.columns where  \
        table_schema = '" + dbName + "' and table_name = '" + tableName + "'"
    conn = getConn()
    cur = getCur(conn)
    count = cur.execute(sql)
    columns = cur.fetchall()
    cur.close()
    conn.commit()
    conn.close()

    return columns

#查询表注释
def getTableComment(dbName,tableName):
    sql = "SELECT table_comment FROM information_schema.TABLES where table_name = '"+tableName+"' and table_schema = '"+dbName+"'"
    conn = getConn()
    cur = getCur(conn)
    count = cur.execute(sql)
    tableComment = cur.fetchall()
    cur.close()
    conn.commit()
    conn.close()
    return tableComment

#数据库数据类型转java数据类型
def convertDataType(dbType):
    if dbType == "int" or dbType == "tinyint":
        return "int"
    elif dbType == "varchar" or dbType =="char" or dbType == "longtext" or dbType == "text":
        return "String"
    elif dbType == "timestamp" or dbType == "date" or dbType=="datetime":
        return "Date"
    elif dbType == "bigint":
        return "long"
    elif dbType == "decimal":
        return "Double"
    
#数据库字段转驼峰式命名
def convertToCalm(field):
    returnValue = ""
    if field.find("_") >= 0:
        subs = field.split("_")
        for index,sub in enumerate(subs):
            if index == 0:
                returnValue = returnValue + sub
            else:
                returnValue = returnValue + sub.capitalize()
        return returnValue
    else:
        return field

#创建实体字段
def createJavaField(columns):
    rv = ""
    for col in columns:
        rv = rv + '\t//'+col[2]+'\n'
        rv = rv + "\tprivate " + convertDataType(col[1]) + " " + convertToCalm(col[0]) + ";\n\n"
    return rv

#生成getter和setter
def createGetterAndSetter(columns):
    rv = ""
    for col in columns:
        rv = rv + "\tpublic " + convertDataType(col[1]) + " get" + getClassName(col[0]) + "() {\n"
        rv = rv + "\t\treturn " + convertToCalm(col[0]) + ";\n" + "\t" + "}\n\n"
        rv = rv + "\tpublic void " + "set" + getClassName(col[0]) + "(" + convertDataType(col[1]) + " "
        rv = rv + convertToCalm(col[0]) + ") " + "{\n"
        rv = rv + "\t\tthis." + convertToCalm(col[0]) + " = " + convertToCalm(col[0]) + ";\n"
        rv = rv + "\t}\n\n"

    return rv


#获取时间,用于生成注释
def getSystemDate():
    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

#类注释
def getBlockComment(tableComment,desc):
    comment = "/**\n * @desc " + tableComment + desc + "\n * @author admin\n * @date "+getSystemDate()+"\n * \n */\n"
    return comment
#空参构造方法
def noArgConstructor(shortTableName):
    nc = ""
    nc = nc + "\tpublic " + getClassName(shortTableName) + "Entity(){}\n\n"
    return nc;

#全参构造方法
def allArgConstructor(shortTableName,columns):
    ac = ""
    ac = ac + "\tpublic " + getClassName(shortTableName) + "Entity("
    for col in columns:
        ac = ac +convertDataType(col[1]) + " " + convertToCalm(col[0]) + ","
    ac = ac.rstrip(",")
    
    ac = ac + "){\n"
    for col in columns:
        ac = ac + "\t\t"+"this." + convertToCalm(col[0]) + " = " + convertToCalm(col[0]) + ";\n"
    ac = ac + "\t}\n\n"

    return ac

#entity路径
def getEntityUrl():
    url = ""
    if len(entityPackage.strip()) > 0:
        url = packageUrl + "." + entityPackage
    else:
        url = packageUrl + ".entity"
    return url

#dao文件路径
def getDaoUrl():
    url = ""
    if len(daoPackage.strip()) > 0:
        url = packageUrl + "." + daoPackage
    else:
        url = packageUrl + ".dao"
    return url

#service文件路径
def getServiceUrl():
    url = ""
    if len(servicePackage.strip()) > 0:
        url = packageUrl + "." + servicePackage
    else:
        url = packageUrl + ".service"
    return url

#service.impl文件路径
def getServiceImplUrl():
    url = ""
    if len(servicePackage.strip()) > 0:
        url = packageUrl + "." + servicePackage + ".impl"
    else:
        url = packageUrl + ".service.impl"
    return url

#controller路径
def getControllerUrl():
    url = ""
    if len(controllerPackage.strip()) > 0:
        url = packageUrl + "." + controllerPackage
    else:
        url = packageUrl + ".controller"
    return url

#生成entity
def createEntity():
    #返回的tables对象是二维元组
    tables = getTablesDic()
    for table in tables:
        tableName = table[0]
        tableId = table[0][0]

        entity = ""
        columns = getTableColumns(dbName,tableName)

        tableComment = getTableComment(dbName,tableName)[0][0]

        #去掉表名前缀
        shortTableName = tableName.replace(prefix,"")

        entity = entity + "package " + getEntityUrl()  + ";\n\n"
        entity = entity + "import java.io.Serializable;\n\n";
        entity = entity + "import java.util.Date;\n\n"
        entity = entity + getBlockComment(tableComment,'实体类')
        entity = entity + "public class " + getClassName(shortTableName) + "Entity implements Serializable{\n\n"
        entity = entity + "\tprivate static final long serialVersionUID = 1L;\n\n"
        # 字段列表
        entity = entity + createJavaField(columns)
        # 无参构造方法
        entity = entity + noArgConstructor(shortTableName)
        # 全参构造方法
        entity = entity + allArgConstructor(shortTableName,columns)
        #getter setter方法
        entity = entity + createGetterAndSetter(columns)
        entity = entity + "}"
        dirs = basePath + "entity/"
        if not os.path.exists(dirs):
            os.makedirs(dirs)
        entityFile = codecs.open(basePath + "entity/" + getClassName(tableName)+"Entity.java", "w", "utf-8")
        entityFile.write(entity)
        entityFile.close()

#生成dao
def createDao():
    tables = getTablesDic()
    for table in tables:
        tableName = table[0]
        tableId = table[0][0]

        tableComment = getTableComment(dbName,tableName)[0][0]
        
        shortTableName = tableName.lstrip(prefix)
        
        dao = ""
        dao = dao + "package " + getDaoUrl() + ";\n\n"
        dao = dao + "import java.util.List;\n\n"
        dao = dao + "import " + getEntityUrl() + "." + getClassName(shortTableName) + "Entity;\n\n" 
        dao = dao + getBlockComment(tableComment,'Dao接口')
        dao = dao + "public interface " + getClassName(shortTableName) + "Dao{\n\n"
        dao = dao + "\t/**\n\t* 按条件查询 \n\t* @param "+convertToCalm(shortTableName)+" \n\t* @return \n\t*/\n"
        dao = dao + '\tList<' + getClassName(shortTableName) + "Entity" + '> findByCondition('+ getClassName(shortTableName) +'Entity ' + convertToCalm(shortTableName)  +');\n\n'
        dao = dao + "\t/**\n\t * 根据Id查询 \n\t * @param "+convertToCalm(tableId)+"\n\t * @return \n\t */\n"
        dao = dao + '\t' + getClassName(shortTableName) + "Entity" + ' findById(String ' + convertToCalm(tableId) + ');\n\n'
        dao = dao + "\t/**\n\t * 保存 \n\t * @param "+convertToCalm(shortTableName)+" \n\t * @return \n\t */\n"
        dao = dao + '\tint save(' + getClassName(tableName) + 'Entity ' + convertToCalm(tableName) + ');\n\n'
        dao = dao + "\t/**\n\t * 更新 \n\t * @param "+convertToCalm(tableName)+" \n\t * @return \n\t */\n"
        dao = dao + '\tint update(' + getClassName(tableName) + 'Entity ' + convertToCalm(tableName) + ');\n\n'
        dao = dao + "\t/**\n\t * 根据Id删除 \n\t * @param "+convertToCalm(tableId)+" \n\t * @return \n\t */\n"
        dao = dao + '\tint deleteById(String ' + convertToCalm(tableId) + ');\n\n'
        dao = dao + "\t/**\n\t * 批量保存 \n\t * @param list \n\t * @return \n\t */\n"
        dao = dao + '\tint batchSave(List<' + getClassName(tableName) + 'Entity> ' + 'list);\n\n'
        dao = dao + "\t/**\n\t * 批量更新 \n\t * @param list \n\t * @return \n\t */\n"
        dao = dao + '\tint batchUpdate(List<' + getClassName(tableName) + 'Entity> ' + 'list);\n\n'
        dao = dao + "\t/**\n\t * 批量删除 \n\t * @param ids \n\t * @return \n\t */\n"
        dao = dao + '\tint batchDelete(List ids);\n\n'
        dao = dao + "}"

        dirs = basePath + "dao/"
        if not os.path.exists(dirs):
            os.makedirs(dirs)

        daoFile = open(basePath + "dao/" + getClassName(tableName) + 'Dao.java','w')
        daoFile.write(dao)
        daoFile.close()

#生成service
def createService():
    tables = getTablesDic()
    for table in tables:
        tableName = table[0]
        tableId = table[0][0]

        tableComment = getTableComment(dbName,tableName)[0][0]

        service = ""
        service = service + "package " + getServiceUrl() + ";\n\n"
        service = service + "import java.util.List;\n"
        service = service + "import com.github.pagehelper.PageInfo;\n\n"
        service = service + "import " + getEntityUrl() + "." + getClassName(tableName) + "Entity;\n\n" 
        service = service + getBlockComment(tableComment,'Service接口')
        service = service + "public interface " + getClassName(tableName) + "Service{\n\n"
        service = service + "\t/**\n\t* 按条件查询 \n\t* @param "+convertToCalm(tableName)+" \n\t* @return \n\t*/\n"
        service = service + '\tList<' + getClassName(tableName) + "Entity" + '> findByCondition('+ getClassName(tableName) + 'Entity ' + convertToCalm(tableName)  +');\n\n'
        service = service + "\t/**\n\t * 分页查询 \n\t * @param \n\t * @return \n\t */\n"
        service = service + '\tPageInfo<'+getClassName(tableName) + 'Entity '+'> findByPage(int pageNum, int pageSize, '+getClassName(tableName) + 'Entity ' + convertToCalm(tableName)+');\n\n'
        service = service + "\t/**\n\t * 根据Id查询 \n\t * @param "+convertToCalm(tableId)+"\n\t * @return \n\t */\n"
        service = service + '\t' + getClassName(tableName) + "Entity" + ' findById(String ' + convertToCalm(tableId) + ');\n\n'
        service = service + "\t/**\n\t * 保存 \n\t * @param "+convertToCalm(tableName)+" \n\t * @return \n\t */\n"
        service = service + '\tint save(' + getClassName(tableName) + 'Entity ' + convertToCalm(tableName) + ');\n\n'
        service = service + "\t/**\n\t * 更新 \n\t * @param "+convertToCalm(tableName)+" \n\t * @return \n\t */\n"
        service = service + '\tint update(' + getClassName(tableName) + 'Entity ' + convertToCalm(tableName) + ');\n\n'
        service = service + "\t/**\n\t * 根据Id删除 \n\t * @param "+convertToCalm(tableId)+" \n\t * @return \n\t */\n"
        service = service + '\tint deleteById(String ' + convertToCalm(tableId) + ');\n\n'
        service = service + "\t/**\n\t * 批量保存 \n\t * @param list \n\t * @return \n\t */\n"
        service = service + '\tint batchSave(List<' + getClassName(tableName) + 'Entity> ' + 'list);\n\n'
        service = service + "\t/**\n\t * 批量更新 \n\t * @param list \n\t * @return \n\t */\n"
        service = service + '\tint batchUpdate(List<' + getClassName(tableName) + 'Entity> ' + 'list);\n\n'
        service = service + "\t/**\n\t * 批量删除 \n\t * @param ids \n\t * @return \n\t */\n"
        service = service + '\tint batchDelete(List ids);\n\n'
        service = service + "}"

        dirs = basePath + "service/"
        if not os.path.exists(dirs):
            os.makedirs(dirs)

        serviceFile = open(basePath + "service/" + getClassName(tableName) + 'Service.java', 'w')
        serviceFile.write(service)
        serviceFile.close()

#生成service实现类
def createServiceImpl():
    tables = getTablesDic()
    for table in tables:
        tableName = table[0]
        tableId = table[0][0]

        tableComment = getTableComment(dbName,tableName)[0][0]

        service = ""
        service = service + "package " + getServiceImplUrl() + ";\n\n"
        service = service + "import java.util.List;\n\n"
        
        service = service + "import org.slf4j.Logger;\n"
        service = service + "import org.slf4j.LoggerFactory;\n"
        service = service + "import org.springframework.beans.factory.annotation.Autowired;\n"
        service = service + "import org.springframework.stereotype.Service;\n\n"

        service = service + "import com.github.pagehelper.PageHelper;\n"
        service = service + "import com.github.pagehelper.PageInfo;\n"
        service = service + "import " + getEntityUrl() + "." + getClassName(tableName) + "Entity;\n"
        service = service + "import " + getDaoUrl() + "." + getClassName(tableName) + "Dao;\n"
        service = service + "import " + getServiceUrl() + "." + getClassName(tableName) + "Service;\n\n"

        service = service + getBlockComment(tableComment,'Service实现')
        service = service + "@Service\n"
        service = service + "public class " + getClassName(tableName) + "ServiceImpl implements " + getClassName(tableName) + "Service{\n\n"
        
        service = service + "\tprivate static final Logger logger = LoggerFactory.getLogger("+getClassName(tableName)+"ServiceImpl.class);\n\n"

        service = service + "\t@Autowired\n"
        service = service + "\tprivate "+ getClassName(tableName) + "Dao " + convertToCalm(tableName) + "Dao;\n\n"
        
        service = service + "\t@Override\n"
        service = service + '\tpublic List<' + getClassName(tableName) + "Entity" + '> findByCondition('+ getClassName(tableName) + 'Entity ' + convertToCalm(tableName)  +'){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.findByCondition");\n'
        service = service + "\t\treturn this." + convertToCalm(tableName)+"Dao."+"findByCondition("+convertToCalm(tableName)+");\n"
        service = service + "\t}\n\n"

        service = service + "\t@Override\n"
        service = service + '\tpublic PageInfo<'+getClassName(tableName) + 'Entity '+'> findByPage(int pageNum, int pageSize, '+getClassName(tableName) + 'Entity ' + convertToCalm(tableName)+'){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.findByPage");\n'
        service = service + '\t\tPageHelper.startPage(pageNum, pageSize, true);\n'
        service = service + '\t\tList<'+getClassName(tableName) + 'Entity'+'> list = findByCondition('+convertToCalm(tableName)+');\n'
        service = service + '\t\tPageInfo<'+getClassName(tableName) + 'Entity'+'> page = new PageInfo<'+getClassName(tableName) + 'Entity'+'>(list);\n'
        service = service + '\t\treturn page;\n'
        service = service + '\t}\n\n'
        
        service = service + "\t@Override\n"
        service = service + '\tpublic ' + getClassName(tableName) + "Entity" + ' findById(String ' + convertToCalm(tableId) + '){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.findById");\n'
        service = service + '\t\treturn this.' + convertToCalm(tableName)+ 'Dao.findById(' + convertToCalm(tableId) + ');\n'
        service = service + '\t}\n\n'
        
        service = service + "\t@Override\n"
        service = service + '\tpublic int save(' + getClassName(tableName) + 'Entity ' + convertToCalm(tableName) + '){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.save");\n'
        service = service + '\t\treturn this.' + convertToCalm(tableName) +'Dao.save(' + convertToCalm(tableName) + ');\n'
        service = service + '\t}\n\n'

        service = service + "\t@Override\n"
        service = service + '\tpublic int update(' + getClassName(tableName) + 'Entity ' + convertToCalm(tableName) + '){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.update");\n'
        service = service + '\t\treturn this.' + convertToCalm(tableName) + 'Dao.update(' + convertToCalm(tableName) + ');\n'
        service = service + '\t}\n\n'

        service = service + "\t@Override\n"
        service = service + '\tpublic int deleteById(String ' + convertToCalm(tableId) + '){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.deleteById");\n'
        service = service + '\t\treturn this.' + convertToCalm(tableName) + 'Dao.deleteById(' + convertToCalm(tableId) + ');\n'
        service = service + '\t}\n\n'

        service = service + "\t@Override\n"
        service = service + '\tpublic int batchSave(List<' + getClassName(tableName) + 'Entity> ' + 'list){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.batchSave");\n'
        service = service + '\t\treturn this.' + convertToCalm(tableName) + 'Dao.batchSave(list);\n'
        service = service + '\t}\n\n'

        service = service + "\t@Override\n"
        service = service + '\tpublic int batchUpdate(List<' + getClassName(tableName) + 'Entity> ' + 'list){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.batchUpdate");\n'
        service = service + '\t\treturn this.' + convertToCalm(tableName) + 'Dao.batchUpdate(list);\n'
        service = service + '\t}\n\n'

        service = service + "\t@Override\n"
        service = service + '\tpublic int batchDelete(List ids){\n'
        service = service + '\t\tlogger.info("'+getClassName(tableName)+'ServiceImpl.batchDelete");\n'
        service = service + '\t\treturn this.' + convertToCalm(tableName) + 'Dao.batchDelete(ids);\n'
        service = service + '\t}\n\n'
        service = service + "}"

        dirs = basePath + "serviceImpl/"
        if not os.path.exists(dirs):
            os.makedirs(dirs)

        serviceFile = open(basePath + "serviceImpl/" + getClassName(tableName) + 'ServiceImpl.java', 'w')
        serviceFile.write(service)
        serviceFile.close()


#生成mapper文件
def createMapper():
    baseSpace = getDaoUrl()
    entityUrl = getEntityUrl()
    tables = getTablesDic()
    for table in tables:
        tableName = table[0]
        tableId = table[0][0]

        # xml header
        mapper = '\n'
        mapper = mapper + '
        mapper = mapper + '\tPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"\n'
        mapper = mapper + '\t"http://mybatis.org/dtd/mybatis-3-mapper.dtd">\n\n'

        mapper = mapper + '+ baseSpace + '.' + getClassName(tableName) +'Dao">\n\n'
        
        #select by conditions
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\n\n'

        # insert method
        mapper = mapper + '\t\n'
        mapper = mapper + '\t+getEntityUrl()+'.'+getClassName(tableName)+'Entity">\n'
        mapper = mapper + '\t\tINSERT INTO ' + tableName + '\n'
        mapper = mapper + '\t\t\t('
        columns1 = columns[0:-2]
        for col in columns1:
            if col[0] != tableId:
                mapper = mapper + col[0] + ','
        mapper = mapper[0:-1] + ')\n'
        mapper = mapper + '\t\tVALUES\n'
        mapper = mapper + '\t\t\t('
        for col in columns1:
            if col[0] != tableId:
                mapper = mapper + '#{' + convertToCalm(col[0]) + '},'
        mapper = mapper[0:-1] + ')\n'
        mapper = mapper + '\t\n\n'

        # update method
        mapper = mapper + '\t\n'
        mapper = mapper + '\t+getEntityUrl()+'.'+getClassName(tableName)+'Entity">\n'
        mapper = mapper + '\t\tUPDATE '+ tableName + ' SET\n'
        for col in columns1:
            if col[0] != tableId:
                mapper = mapper + '\t\t\t' + col[0] + ' = ' + '#{' + convertToCalm(col[0]) + '},\n'
        mapper = mapper[0:-2] + '\n'
        mapper = mapper + '\t\tWHERE\n'
        mapper = mapper + '\t\t\t'
        mapper = mapper + tableId + ' = ' + '#{'+ convertToCalm(tableId) + '}\n'
        mapper = mapper + '\t\n\n'

        # delete method
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\tDELETE FROM ' + tableName + ' WHERE ' + tableId + ' = ' + '#{' + convertToCalm(tableId) + '}\n'
        mapper = mapper + '\t\n\n'

        # batchSave method
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\tINSERT INTO ' + tableName + ' (\n'
        for col in columns1:
            if col[0] != tableId:
                mapper = mapper + '\t\t\t' + col[0] + ',\n'
        mapper = mapper[0:-2] + '\n'
        mapper = mapper + '\t\t)\n'
        mapper = mapper + '\t\tVALUES\n'
        mapper = mapper + '\t\t\n'
        mapper = mapper + "\t\t(\n"
        for col in columns1:
            if col[0] != tableId:
                mapper = mapper + '\t\t\t#{item.' + convertToCalm(col[0]) + '},\n'
        mapper = mapper[0:-2] + '\n'
        mapper = mapper + "\t\t)\n"
        mapper = mapper + "\t\t)\n"
        mapper = mapper + '\t\n\n'

        # batchUpdate method
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\t\n'
        mapper = mapper + '\t\t\tupdate '+tableName+'\n'
        mapper = mapper + '\t\t\t\n'
        for col in columns1:
            if col[0] != tableId:
                mapper = mapper + '\t\t\t\t' + col[0] + ' = ' + '#{' + convertToCalm(col[0]) + '},\n'
        mapper = mapper[0:-2] + '\n'
        mapper = mapper + '\t\t\t\n'
        mapper = mapper + '\t\t\twhere '+tableId+' = #{item.'+convertToCalm(tableId)+'}\n'
        mapper = mapper + '\t\t\n'
        mapper = mapper + '\t\n\n'

        # batchUpdate method
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\n'
        mapper = mapper + '\t\tdelete from '+tableName+' where '+tableId+' in\n'
        mapper = mapper + '\t\t\n'
        mapper = mapper + '\t\t\t#{item}\n'
        mapper = mapper + '\t\t\n'
        mapper = mapper + '\t\n\n'


        mapper = mapper + ''
        
        dirs = basePath + "mapper/"
        if not os.path.exists(dirs):
            os.makedirs(dirs)

        mapperFile = open(basePath + "mapper/" + getClassName(tableName) + 'Mapper.xml', 'w')
        mapperFile.write(mapper)
        mapperFile.close()

def createController():
    tables = getTablesDic()

    for table in tables:
        tableName = table[0]
        tableId = table[0][0]

        tableComment = getTableComment(dbName,tableName)[0][0]

        con = ''
        con = con + 'package ' + getControllerUrl() + ';\n\n'
        con = con + getBlockComment(tableComment,'REST接口')
        con = con + '@Controller\n'
        con = con + '@RequestMapping("/'+moduleName+'")\n'
        con = con + 'public class '+getClassName(tableName)+'Controller{\n\n'

        con = con + '\tprivate static final Logger logger = LoggerFactory.getLogger('+getClassName(tableName)+'Controller.class);\n\n'
        
        con = con + '\t@Autowired\n'
        con = con + '\tprivate ' + getClassName(tableName) + 'Service ' + convertToCalm(tableName) + 'Service;\n\n'

        # find by page
        con = con + "\t/**\n\t* 分页查询 \n\t* @author admin \n\t* @return PageInfo<"+getClassName(tableName)+"Entity>\n\t*/\n"
        con = con + '\t@RequestMapping("/findByPage'+'/{pageNum}/{pageSize}")\n'
        con = con + '\tpublic String findByPage(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize, '+getClassName(tableName)+'Entity '+convertToCalm(tableName)+', Model model){\n'
        con = con + '\t\ttry{\n'
        con = con + '\t\t\tPageInfo<'+getClassName(tableName)+'Entity> page = this.'+convertToCalm(tableName)+'Service.findByPage(pageNum,pageSize,'+convertToCalm(tableName)+');\n'
        con = con + '\t\t\tmodel.addAttribute("page", page);\n'
        con = con + '\t\t\treturn "'+moduleName+'/'+convertToCalm(tableName)+'";\n'
        con = con + '\t\t} catch (Exception e) {\n'
        con = con + '\t\t\te.printStackTrace();\n'
        con = con + '\t\t\treturn "error";\n'
        con = con + '\t\t}\n'
        con = con + '\t}\n\n'

        #list
        con = con + "\t/**\n\t* 条件查询 \n\t* @author admin \n\t* @return List<"+getClassName(tableName)+"Entity>\n\t*/\n"
        con = con + '\t@RequestMapping("/findByCondition'+'")\n'
        con = con + '\tpublic String findByCondition(Model model,'+getClassName(tableName)+'Entity '+convertToCalm(tableName)+'){\n'
        con = con + '\t\ttry{\n'
        con = con + '\t\t\tList<'+getClassName(tableName)+'Entity> list = this.'+convertToCalm(tableName)+'Service.findByCondition('+convertToCalm(tableName)+');\n'
        con = con + '\t\t\tmodel.addAttribute("list", list);\n'
        con = con + '\t\t\treturn "'+moduleName+'/'+convertToCalm(tableName)+'";\n'
        con = con + '\t\t} catch (Exception e) {\n'
        con = con + '\t\t\te.printStackTrace();\n'
        con = con + '\t\t\treturn "error";\n'
        con = con + '\t\t}\n'
        con = con + '\t}\n\n'

        # save
        con = con + "\t/**\n\t* 保存 \n\t* @author admin \n\t* @return String\n\t*/\n"
        con = con + '\t@ResponseBody\n'
        con = con + '\t@RequestMapping("/save'+'")\n'
        con = con + '\tpublic String save('+getClassName(tableName)+'Entity '+convertToCalm(tableName)+', Model model){\n'
        con = con + '\t\ttry{\n'
        con = con + '\t\t\tint count = this.'+convertToCalm(tableName)+'Service.save('+convertToCalm(tableName)+');\n'
        con = con + '\t\t\tif(count > 0) {\n'
        con = con + '\t\t\t\treturn "1";\n'
        con = con + '\t\t\t}else{\n'
        con = con + '\t\t\t\treturn "0";\n'
        con = con + '\t\t\t}\n'
        con = con + '\t\t} catch (Exception e) {\n'
        con = con + '\t\t\te.printStackTrace();\n'
        con = con + '\t\t\treturn "-1";\n'
        con = con + '\t\t}\n'
        con = con + '\t}\n\n'

        #update
        con = con + "\t/**\n\t* 更新 \n\t* @author admin \n\t* @return String\n\t*/\n"
        con = con + '\t@ResponseBody\n'
        con = con + '\t@RequestMapping("/update'+'")\n'
        con = con + '\tpublic String update('+getClassName(tableName)+'Entity '+convertToCalm(tableName)+', Model model){\n'
        con = con + '\t\ttry{\n'
        con = con + '\t\t\tint count = this.'+convertToCalm(tableName)+'Service.update('+convertToCalm(tableName)+');\n'
        con = con + '\t\t\tif(count > 0) {\n'
        con = con + '\t\t\t\treturn "1";\n'
        con = con + '\t\t\t}else{\n'
        con = con + '\t\t\t\treturn "0";\n'
        con = con + '\t\t\t}\n'
        con = con + '\t\t} catch (Exception e) {\n'
        con = con + '\t\t\te.printStackTrace();\n'
        con = con + '\t\t\treturn "-1";\n'
        con = con + '\t\t}\n'
        con = con + '\t}\n\n'

        #delete
        con = con + "\t/**\n\t* 删除 \n\t* @author admin \n\t* @return String\n\t*/\n"
        con = con + '\t@ResponseBody\n'
        con = con + '\t@RequestMapping("/delete'+'")\n'
        con = con + '\tpublic String delete(String id, Model model){\n'
        con = con + '\t\ttry{\n'
        con = con + '\t\t\tint count = this.'+convertToCalm(tableName)+'Service.deleteById(id);\n'
        con = con + '\t\t\tif(count > 0) {\n'
        con = con + '\t\t\t\treturn "1";\n'
        con = con + '\t\t\t}else{\n'
        con = con + '\t\t\t\treturn "0";\n'
        con = con + '\t\t\t}\n'
        con = con + '\t\t} catch (Exception e) {\n'
        con = con + '\t\t\te.printStackTrace();\n'
        con = con + '\t\t\treturn "-1";\n'
        con = con + '\t\t}\n'
        con = con + '\t}\n\n'

        # batch save
        con = con + "\t/**\n\t* 批量保存 \n\t* @author admin \n\t* @return String\n\t*/\n"
        con = con + '\t@ResponseBody\n'
        con = con + '\t@RequestMapping("/batchSave'+'")\n'
        con = con + '\tpublic String batchSave(List<'+getClassName(tableName)+'Entity> list, Model model){\n'
        con = con + '\t\ttry{\n'
        con = con + '\t\t\tint count = this.'+convertToCalm(tableName)+'Service.batchSave(list);\n'
        con = con + '\t\t\tif(count > 0) {\n'
        con = con + '\t\t\t\treturn "1";\n'
        con = con + '\t\t\t}else{\n'
        con = con + '\t\t\t\treturn "0";\n'
        con = con + '\t\t\t}\n'
        con = con + '\t\t} catch (Exception e) {\n'
        con = con + '\t\t\te.printStackTrace();\n'
        con = con + '\t\t\treturn "-1";\n'
        con = con + '\t\t}\n'
        con = con + '\t}\n\n'

        # batch update
        con = con + "\t/**\n\t* 批量更新 \n\t* @author admin \n\t* @return String\n\t*/\n"
        con = con + '\t@ResponseBody\n'
        con = con + '\t@RequestMapping("/batchUpdate'+'")\n'
        con = con + '\tpublic String batchUpdate(List<'+getClassName(tableName)+'Entity> list, Model model){\n'
        con = con + '\t\ttry{\n'
        con = con + '\t\t\tint count = this.'+convertToCalm(tableName)+'Service.batchUpdate(list);\n'
        con = con + '\t\t\tif(count > 0) {\n'
        con = con + '\t\t\t\treturn "1";\n'
        con = con + '\t\t\t}else{\n'
        con = con + '\t\t\t\treturn "0";\n'
        con = con + '\t\t\t}\n'
        con = con + '\t\t} catch (Exception e) {\n'
        con = con + '\t\t\te.printStackTrace();\n'
        con = con + '\t\t\treturn "-1";\n'
        con = con + '\t\t}\n'
        con = con + '\t}\n\n'

        # batch delete
        con = con + "\t/**\n\t* 批量删除 \n\t* @author admin \n\t* @return String\n\t*/\n"
        con = con + '\t@ResponseBody\n'
        con = con + '\t@RequestMapping("/batchDelete'+'")\n'
        con = con + '\tpublic String batchDelete(List ids, Model model){\n'
        con = con + '\t\ttry{\n'
        con = con + '\t\t\tint count = this.'+convertToCalm(tableName)+'Service.batchDelete(ids);\n'
        con = con + '\t\t\tif(count > 0) {\n'
        con = con + '\t\t\t\treturn "1";\n'
        con = con + '\t\t\t}else{\n'
        con = con + '\t\t\t\treturn "0";\n'
        con = con + '\t\t\t}\n'
        con = con + '\t\t} catch (Exception e) {\n'
        con = con + '\t\t\te.printStackTrace();\n'
        con = con + '\t\t\treturn "-1";\n'
        con = con + '\t\t}\n'
        con = con + '\t}\n\n'
        
        con = con + '}\n'

        dirs = basePath + "controller/"
        if not os.path.exists(dirs):
            os.makedirs(dirs)

        conFile = open(basePath + "controller/" + getClassName(tableName) + 'Controller.java', 'w')
        conFile.write(con)
        conFile.close()

if __name__  == "__main__":
    createEntity()
    createDao()
    createService()
    createServiceImpl()
    createMapper()
    createController()

你可能感兴趣的:(python能做的100件事,python,开发语言,java,源代码管理)