from lib2to3.pytree import convert
from struct import pack
import time
import datetime
from glob import glob
from tkinter import filedialog
import tkinter as tk
import os
import shutil
import cx_Oracle
import xml.dom.minidom
from matplotlib.pyplot import table
import yaml
import tkinter.messagebox as msgbox
import traceback
import sys
config_dict = {}
now = datetime.datetime.now()
#读取xml文件
def get_info_from_xml():
xml_file = xml.dom.minidom.parse("Connect2Oracle\generator.xml")
xml_file.find("author").text()
print(xml_file.find("author").text)
print('---')
def get_yaml_data():
f = open('Connect2Oracle\\application.yml', encoding='utf-8')
# 设置Loader=yaml.FullLoader忽略YAMLLoadWarning警告
return yaml.load(f,Loader=yaml.FullLoader)
#半驼峰 如字段名为 scc_locked_id 会转成 sccLockedId
def convert_half_camel(one_string,space_character):
string_list = str(one_string).split(space_character) #将字符串转化为list
first = string_list[0].lower()
others = string_list[1:]
others_capital = [word.capitalize() for word in others] #str.capitalize():将字符串的首字母转化为大写
others_capital[0:0] = [first]
hump_string = ''.join(others_capital) #将list组合成为字符串,中间无连接符。
return hump_string
#驼峰 如字段名为 scc_locked_id 会转成 SccLockedId
def convert_camel(one_string,space_character):
string_list = str(one_string).split(space_character) #将字符串转化为list
others_capital = [word.capitalize() for word in string_list] #str.capitalize():将字符串的首字母转化为大写
hump_string = ''.join(others_capital) #将list组合成为字符串,中间无连接符。
return hump_string
def connect_OK():
config_dict = get_yaml_data()
username = config_dict['username']
password = config_dict['password']
host = config_dict['host']
port = config_dict['port']
servicename = config_dict['servicename']
try:
conn = cx_Oracle.connect(username,password, host + ':' + str(port) + '/' + servicename)
cursor = conn.cursor ()
msgbox.showinfo('温馨提示', '连接成功!')
except Exception as ex_results:
msg = traceback.format_exc()
msgbox.showinfo('温馨提示', msg)
def connect_2_oracle():
table_name = text4.get().upper()
if len(table_name) == 0:
msgbox.showinfo('温馨提示', '请输入表名!')
# sys.exit(0)
# os._exit
return
config_dict = get_yaml_data()
package = config_dict['package']
author = config_dict['author']
schema = config_dict['schema']
username = config_dict['username']
password = config_dict['password']
host = config_dict['host']
port = config_dict['port']
servicename = config_dict['servicename']
conn = cx_Oracle.connect(username,password, host + ':' + str(port) + '/' + servicename)
cursor = conn.cursor ()
execute_sql_for_table_values = "SELECT * FROM {}".format(table_name)
cursor.execute (execute_sql_for_table_values)
table_values = cursor.fetchall() #得到表数据集
col_names = [x[0] for x in cursor.description] #获取列名
execute_sql_for_field = "select ut.COLUMN_NAME, uc.comments, ut.DATA_TYPE, ut.DATA_LENGTH, ut.NULLABLE from all_tab_columns ut inner JOIN all_col_comments uc on ut.TABLE_NAME = uc.table_name and ut.COLUMN_NAME = uc.column_name where ut.Table_Name= '{}' order by ut.column_name ".format(table_name.upper())
cursor.execute (execute_sql_for_field)
field_values = cursor.fetchall() #得到字段类型、字段注释等数据集
execute_sql_for_pk = "select cu.* from all_cons_columns cu, all_constraints au where cu.constraint_name = au.constraint_name and au.constraint_type = 'P' and au.table_name = '{}'".format(table_name.upper())
cursor.execute (execute_sql_for_pk)
pk_values = cursor.fetchall() #得到字段类型、字段注释等数据集
execute_sql_for_table_comment = " SELECT a.TABLE_NAME,b.COMMENTS FROM all_tables a,all_tab_comments b WHERE a.TABLE_NAME=b.TABLE_NAME and a.TABLE_NAME = '{}' ORDER BY TABLE_NAME ".format(table_name.upper())
cursor.execute(execute_sql_for_table_comment)
table_comments = cursor.fetchall()#获取表的中文名
table_chinses_name = ''
if(len(table_comments) > 0):
table_chinses_name = table_comments[0][1]
primary_key = ""
if(len(pk_values)> 0):
primary_key = pk_values[0][3]
f=open(convert_camel(table_name,"_") + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f.write("""
package {}.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.copier.CopyOptions;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.sql.Timestamp;
import cn.com.scc.common.base.BaseExtEntity;
/**
*
* @Author {}
* @date {}
**/
@Entity
@Getter
@Setter
@ToString
@Table(name="{}", schema="{}")
""".format(package,author,now.strftime('%Y-%m-%d %H:%M:%S'),table_name,schema))
f.writelines("""
public class {} extends BaseExtEntity implements Serializable {}
private static final long serialVersionUID = 1L;
""".format(convert_camel(table_name,"_"),"{"))
# 0:'AUTH_TYPE'
# 1:'授权类型'
# 2:'VARCHAR2'
# 3:20
# 4:'Y'
for index in field_values:
if (primary_key == index[0]):
f.writelines("""
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator={})
@SequenceGenerator(name="{}", sequenceName={}, allocationSize = 1, schema={})
@Column(name = "{}")
@ApiModelProperty(value = "{}")
private Long {};
""".format(table_name.upper()+"_S",table_name.upper()+"_S",table_name.upper()+"_S",schema,primary_key,index[1],convert_half_camel(primary_key,'_')))
elif('DATE' == index[2]):
if(index[4] == 'Y'):
f.writelines("""
@Column(name = "{}", nullable = true)
@ApiModelProperty(value = "{}")
private Timestamp {};
""".format(index[0],index[1],convert_half_camel(index[0],"_")))
else:
f.writelines("""
@Column(name = "{}", nullable = false)
@NotNull
@ApiModelProperty(value = "{}")
private Timestamp {};
""".format(index[0],index[1],convert_half_camel(index[0],"_")))
elif('VARCHAR2' == index[2]):
if(index[4] == 'Y'):
f.writelines("""
@Column(name = "{}", nullable = true, length = {})
@ApiModelProperty(value = "{}")
private String {};
""".format(index[0],index[3],index[1],convert_half_camel(index[0],"_")))
else:
f.writelines("""
@Column(name = "{}", nullable = false, length = {})
@NotBlank
@ApiModelProperty(value = "{}")
private String {};
""".format(index[0],index[3],index[1],convert_half_camel(index[0],"_")))
else:
if(index[4] == 'Y'):
f.writelines("""
@Column(name = "{}", nullable = true)
@ApiModelProperty(value = "{}")
private Long {};""".format(index[0],index[3],index[1],convert_half_camel(index[0],"_")))
else:
f.writelines("""
@Column(name = "{}", nullable = false, length = {})
@NotBlank
@ApiModelProperty(value = "{}")
private Long {};
""".format(index[0],index[3],index[1],convert_half_camel(index[0],"_")))
f.writelines("""
public void copy({} source){}
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
{}
{}""".format(convert_camel(table_name,"_"),"{","}","}"))
f.close()
#生成service
f_service=open('I' + convert_camel(table_name,"_")+ 'Service' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f_service.writelines("""
package {}.service;
import {}.dto.ProcessAbnormalTriggerDTO;
import {}.model.ProcessAbnormalTrigger;
import {}.vo.ProcessAbnormalTriggerQueryVO;
import org.springframework.data.domain.Pageable;
import cn.com.scc.common.page.PageTableData;
import java.util.List;
import java.util.Set;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author {}
* @date {}
**/
public interface {} {}
/**
* 查询数据分页
* @param criteria 条件
* @param pageable 分页参数
* @return Map<String,Object>
*/
public PageTableData queryAll({}VO criteria, Pageable pageable);
/**
* 查询所有数据不分页
* @param criteria 条件参数
* @return List<{}DTO>
*/
public List<{}DTO> queryAll({}VO criteria);
/**
* 根据ID查询
* @param id ID
* @return {}DTO
*/
public {}DTO findById(Long id);
/**
* 创建
* @param resources /
* @return {}DTO
*/
public {}DTO create({} resources);
/**
* 编辑
* @param resources /
*/
public void update({} resources);
/**
* 多选删除
* @param ids /
*/
public void deleteAll(Set<Long> ids);
/**
* 导出数据
* @param all 待导出的数据
* @param response /
* @throws IOException /
*/
public void download(List<{}DTO> all, HttpServletResponse response) throws IOException;
{}
""".format(
package,
package,
package,
package,
author,
now.strftime('%Y-%m-%d %H:%M:%S'),
'I' + convert_camel(table_name,"_")+ 'Service' ,
"{",
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
convert_camel(table_name,'_'),
"}"
))
f_service.close()
f_mapper = open(convert_camel(table_name,"_")+ 'Mapper' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f_mapper.writelines("""
package {}.mapstruct;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
import cn.com.scc.common.base.BaseMapper;
import {}.dto.{}DTO;
import {}.model.{};
/**
*
* @author {}
* @date {}
**/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface {}Mapper extends BaseMapper<{}DTO, {}> {}
{}
""".format(package,package,convert_camel(table_name,'_'),package,convert_camel(table_name,'_'),author,now.strftime('%Y-%m-%d %H:%M:%S'), convert_camel(table_name,'_'),convert_camel(table_name,'_'),convert_camel(table_name,'_'),"{","}" ))
f_mapper.close()
#生成VO
f_VO=open(convert_camel(table_name,"_")+ 'VO' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f_VO.writelines("""
package {}.vo;
import cn.com.scc.common.annotation.JpaConvert;
import cn.com.scc.common.base.BaseExtDTO;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.math.BigDecimal;
/**
*
* @author {}
* @date {}
**/
@Getter
@Setter
@ToString
public class {}VO implements Serializable {}
private static final long serialVersionUID = 1L;
""".format(package,author,now.strftime('%Y-%m-%d %H:%M:%S'),convert_camel(table_name,'_'),"{"))
# 0:'AUTH_TYPE'
# 1:'授权类型'
# 2:'VARCHAR2'
# 3:20 ('DATE' == index[2]):
# 4:'Y'
for index in field_values:
if('NUMBER' == index[2]):
f_VO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_VO.writelines(" private Long " + convert_half_camel(index[0], '_') + ';' + '\n' )
elif('VARCHAR2' == index[2]):
f_VO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_VO.writelines(" private String " + convert_half_camel(index[0], '_') + ';' + '\n' )
else:
f_VO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_VO.writelines(" private Timestamp " + convert_half_camel(index[0], '_') + ';' + '\n' )
f_VO.writelines("""
public {}VO(){}
{}
""".format(convert_camel(table_name,'_'),"{","}"))
# 0:'AUTH_TYPE'
# 1:'授权类型'
# 2:'VARCHAR2'
# 3:20
# 4:'Y'
f_VO.writelines("""
@JpaConvert
public {}VO(""".format(convert_camel(table_name,'_')))
i = 0
for index in field_values:
if(len(field_values) != i +1 ):
if('DATE' == index[2]):
f_VO.writelines('Object ' + convert_half_camel(index[0],'_') + ',' )
elif('VARCHAR2' == index[2]):
f_VO.writelines('String ' + convert_half_camel(index[0],'_') + ',' )
else:
f_VO.writelines('BigDecimal ' + convert_half_camel(index[0],'_') + ',' )
i = i+ 1
else:
if('DATE' == index[2]):
f_VO.writelines('Object ' + convert_half_camel(index[0],'_') + ')' + '{')
elif('VARCHAR2' == index[2]):
f_VO.writelines('String ' + convert_half_camel(index[0],'_')+ ')' + '{')
else:
f_VO.writelines('BigDecimal ' + convert_half_camel(index[0],'_')+ ')' + '{')
for index in field_values:
f_VO.writelines('\n')
if('DATE' == index[2]):
f_VO.writelines("""
this.{} = {} == null ? null :(Timestamp) {};
""".format(convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_')))
elif('VARCHAR2' == index[2]):
f_VO.writelines("""
this.{} = {};
""".format(convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_')))
else:
f_VO.writelines("""
this.{} = {} == null ? null : {}.longValue();
""".format(convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_')))
f_VO.writelines("""
{}
{}
""".format("}","}"))
f_VO.close()
#DTO实现过程
f_DTO=open(convert_camel(table_name,"_")+ 'DTO' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f_DTO.writelines("""
package {}.dto;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.io.Serializable;
import cn.com.scc.common.annotation.JpaConvert;
import cn.com.scc.common.base.BaseExtDTO;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
*
* @author {}
* @date {}
**/
@Getter
@Setter
@ToString
@NoArgsConstructor
public class {}DTO extends BaseExtDTO implements Serializable {}
private static final long serialVersionUID = 1L;
""".format(package,author,now.strftime('%Y-%m-%d %H:%M:%S'),convert_camel(table_name,'_'),"{"))
# 0:'AUTH_TYPE'
# 1:'授权类型'
# 2:'VARCHAR2'
# 3:20
# 4:'Y'
for index in field_values:
if('NUMBER' == index[2]):
f_DTO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_DTO.writelines(" private Long " + convert_half_camel(index[0], '_') + ';' + '\n' )
elif('VARCHAR2' == index[2]):
f_DTO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_DTO.writelines(" private String " + convert_half_camel(index[0], '_') + ';' + '\n' )
else:
f_DTO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_DTO.writelines(" private Timestamp " + convert_half_camel(index[0], '_') + ';' + '\n' )
f_DTO.writelines("""
public {}(){}
{}
""".format(convert_camel(table_name,'_'),"{","}"))
# 0:'AUTH_TYPE'
# 1:'授权类型'
# 2:'VARCHAR2'
# 3:20
# 4:'Y'
f_DTO.writelines("""
@JpaConvert
public {}VO(""".format(convert_camel(table_name,'_')))
i = 0
for index in field_values:
if(len(field_values) != i +1 ):
if('DATE' == index[2]):
f_DTO.writelines('Object ' + convert_half_camel(index[0],'_') + ',' )
elif('VARCHAR2' == index[2]):
f_DTO.writelines('String ' + convert_half_camel(index[0],'_') + ',' )
else:
f_DTO.writelines('BigDecimal ' + convert_half_camel(index[0],'_') + ',' )
i = i+ 1
else:
if('DATE' == index[2]):
f_DTO.writelines('Object ' + convert_half_camel(index[0],'_') + ')' + '{')
elif('VARCHAR2' == index[2]):
f_DTO.writelines('String ' + convert_half_camel(index[0],'_')+ ')' + '{')
else:
f_DTO.writelines('BigDecimal ' + convert_half_camel(index[0],'_')+ ')' + '{')
for index in field_values:
f_DTO.writelines('\n')
if('DATE' == index[2]):
f_DTO.writelines("""
this.{} = {} == null ? null :(Timestamp) {};
""".format(convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_')))
elif('VARCHAR2' == index[2]):
f_DTO.writelines("""
this.{} = {};
""".format(convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_')))
else:
f_DTO.writelines("""
this.{} = {} == null ? null : {}.longValue();
""".format(convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_'), convert_half_camel(index[0],'_')))
f_DTO.writelines("""
{}
{}
""".format("}","}"))
f_DTO.close()
#service实现类
#f_service_impl=open(convert_camel(table_name,"_")+ 'Mapper' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
#DTO实现过程
f_serviceimpl=open(convert_camel(table_name,"_")+ 'ServiceImpl' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f_serviceimpl.writelines("""
package {}.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.scc.common.utils.ValidationUtil;
import cn.com.scc.common.utils.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import cn.com.scc.common.exception.BusinessException;
import cn.com.scc.common.page.PageTableData;
import cn.com.scc.common.utils.PageUtil;
import cn.com.scc.common.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import {}.repository.{};
import {}.service.{};
import {}.dto.{};
import {}.vo.{};
import {}.mapstruct.{};
import {}.model.{};
""".format(package,
package,
convert_camel(table_name, '_') + 'Repository',
package,
'I' + convert_camel(table_name, '_') + 'Service',
package,
convert_camel(table_name,'_') + 'DTO',
package,
convert_camel(table_name,'_') + 'VO',
package,
convert_camel(table_name,'+') + 'Mapper',
package,
convert_camel(table_name, '_')
))
f_serviceimpl.writelines("""
/**
*
* @author {}
* @date {}
**/
@Service(value = {})
public class {} implements {} {}
""".format( author,
now.strftime('%Y-%m-%d %H:%M:%S'),
convert_half_camel(table_name,'_') + 'Service',
convert_camel(table_name,'_') + 'ServiceImpl',
'I' + convert_camel(table_name,'_') + 'Service',
"{"
))
f_serviceimpl.writelines("""
private static final Logger log = LoggerFactory.getLogger({}.class);
@Resource
private {} {};
@Resource
private {} {};
""".format(convert_camel(table_name,'_') + 'ServiceImpl',
convert_camel(table_name,'_') + 'Repository',
convert_half_camel(table_name,'_') + 'Repository',
convert_camel(table_name, '_') + 'Mapper',
convert_half_camel(table_name, '_') + 'Mapper'
))
#查詢方法
f_serviceimpl.writelines("""
@Override
public PageTableData queryAll({} criteria, Pageable pageable){}
Page<{}> page = {}.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPageTable(page.map({}::toDto));
{}
@Override
public List<{}> queryAll({} criteria){}
return {}.toDto({}.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
{}
@Override
public {} findById(Long id) {}
{} {} = {}.findById(id).orElseGet({}::new);
ValidationUtil.isNull({}.getId(),{},"id",id);
return {}.toDto({});
{}
""".format( convert_camel(table_name,'_') + 'QueryVO',
"{",
convert_camel(table_name, '_'),
convert_half_camel(table_name,'_') + 'Repository',
convert_half_camel(table_name,'_') + 'Mapper',
"}",
convert_half_camel(table_name,'_') + 'DTO',
convert_camel(table_name,'_') + 'QueryVO',
"{",
convert_half_camel(table_name,'_') + 'Mapper',
convert_half_camel(table_name,'_') + 'Repository',
"}",
convert_half_camel(table_name,'_') + 'DTO',
"{",
convert_camel(table_name, '_'),
convert_half_camel(table_name, '_'),
convert_half_camel(table_name,'_') + 'Repository',
convert_camel(table_name, '_'),
convert_half_camel(table_name, '_'),
"\"" + convert_camel(table_name, '_') + "\"",
convert_half_camel(table_name,'_') + 'Mapper',
convert_half_camel(table_name,'_'),
"}"
))
f_serviceimpl.writelines("""
@Override
@Transactional
public {} create({} resources) {}
List<Object[]> isExist = {}.findById(resources.getId());
if (isExist.size()>0) {}
throw new BusinessException("ERR-0226");
{}
return {}.toDto({}.save(resources));
{}
@Override
@Transactional
public void update({} resources) {}
{} {} = {}.findById(resources.getId()).orElseGet({}::new);
ValidationUtil.isNull( {}.getId(),{},"id",resources.getId());
{}.copy(resources);
{}.save({})
{}
""".format(convert_camel(table_name,'_') + 'DTO',
convert_camel(table_name,'_'),
"{",
convert_half_camel(table_name,'_') + 'Repository' ,
"{",
"}",
convert_half_camel(table_name,'_') + 'Mapper' ,
convert_half_camel(table_name,'_') + 'Repository',
"}",
convert_camel(table_name,'_'),
"{",
convert_camel(table_name,'_'),
convert_half_camel(table_name,'_'),
convert_half_camel(table_name,'_') + 'Repository',
convert_camel(table_name,'_'),
convert_half_camel(table_name,'_'),
"\"" + convert_camel(table_name,'_') + "\"",
convert_half_camel(table_name,'_'),
convert_half_camel(table_name,'_') + 'Repository',
convert_half_camel(table_name,'_'),
"}" ) )
f_serviceimpl.writelines("""
@Override
@Transactional
public void deleteAll(Set<Long> ids) {}
for (Long id : ids) {}
{}.deleteById(id);
{}
{}""".format("{", "{",convert_half_camel(table_name,'_') + 'Repository', "}" , "}"))
f_serviceimpl.writelines("""
@Override
public void download(List<{}> all, HttpServletResponse response) throws IOException {}
List<Map<String, Object>> list = new ArrayList<>();
for ({} {} : all) {}
""".format(convert_camel(table_name,'_'), "{", convert_camel(table_name, '_'), convert_half_camel(table_name, '_'), "{" ))
for index in field_values:
f_serviceimpl.writelines("""
map.put({},{});""".format("\"" + index[1] + "\"",convert_half_camel(table_name,'_') + 'DTO.get' + convert_camel(index[0], '_') + '()'))
f_serviceimpl.writelines("""
list.add(map);""")
f_serviceimpl.writelines("""
{}
FileUtil.downloadExcel(list, response);
{}
{}
""".format("}","}", "}"))
f_serviceimpl.close()
#dao层数据
f_Dao=open(convert_camel(table_name,"_")+ 'Repository' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f_Dao.writelines("""
package {}.repository;
import {}.model.{};
import cn.com.scc.common.base.BaseRepository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
/**
*
* @author {}
* @date {}
**/
public interface {} extends BaseRepository<{}, Long> {}
{}
""".format(package,
package,
convert_camel(table_name,'_'),
author,
now.strftime('%Y-%m-%d %H:%M:%S'),
convert_camel(table_name,'_') + 'Repository',
convert_camel(table_name,'_'),
"{",
"}"
))
f_Dao.close()
#controller层数据
f_Controller=open(convert_camel(table_name,"_")+ 'Controller' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f_Controller.writelines("""
package {}.web;
import java.util.Set;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.com.scc.common.annotation.Log;
import {}.model.UniqueNumberRule;
import {}.service.IUniqueNumberRuleService;
import {}.vo.UniqueNumberRuleQueryVO;
/**
* @author {}
* @date {}
*/
""".format(package,
package,
package,
package,
author,
now.strftime('%Y-%m-%d %H:%M:%S')
))
f_Controller.writelines("""
@RestController
@Api(tags = "{}")
@RequestMapping("/api/{}")
public class {}Controller {}
private static final Logger log = LoggerFactory.getLogger({}.class);
@Resource
{} {};
""".format(table_chinses_name,
convert_half_camel(table_name,'_'),
convert_camel(table_name,'_'),
"{",
convert_camel(table_name,'_'),
"I" + convert_camel(table_name,'_') + "Service" ,
convert_half_camel(table_name,'_')))
f_Controller.writelines("""
@GetMapping("/download")
@Log("导出数据")
@ApiOperation("导出数据")
@PreAuthorize("@el.check('{}:download')")
public void download(HttpServletResponse response, {} criteria) throws IOException {}
{}.download({}.queryAll(criteria), response);
{}
""".format(convert_half_camel(table_name,'_'),
convert_camel(table_name,'_') + 'QueryVO',
"{",
convert_half_camel(table_name,'_') + 'Service',
convert_half_camel(table_name,'_') + 'Service',
"}"
))
f_Controller.writelines("""
@PostMapping("/create")
@Log("新增{}信息")
@ApiOperation("新增{}信息")
@PreAuthorize("@el.check('{}:add')")
public ResponseEntity<Object> create(@Validated @RequestBody {} resources){}
return new ResponseEntity<>({}.create(resources),HttpStatus.CREATED);
{}
""".format(table_chinses_name,
table_chinses_name,
convert_half_camel(table_name,'_'),
convert_camel(table_name,'_'),
"{",
convert_half_camel(table_name,'_')+ 'Service',
"}"))
f_Controller.writelines("""
@DeleteMapping("/delete")
@Log("删除{}信息")
@ApiOperation("删除{}信息")
@PreAuthorize("@el.check('{}:del')")
public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {}
{}.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
{}
""".format(table_chinses_name,
table_chinses_name,
convert_half_camel(table_name,'_'),
"{",
convert_half_camel(table_name,'_'),
"}"
))
f_Controller.writelines("""
@PutMapping("/update")
@Log("修改{}信息")
@ApiOperation("修改{}信息")
@PreAuthorize("@el.check('{}:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody {} resources){}
{}.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
{}
""".format(table_chinses_name,
table_chinses_name,
convert_half_camel(table_name,'_'),
convert_camel(table_name,'_'),
"{",
convert_half_camel(table_name,'_') + 'Service',
"}"
))
f_Controller.writelines("""
@GetMapping("/queryAllData")
@Log("查询{}信息")
@ApiOperation("查询{}信息")
@PreAuthorize("@el.check('{}:list')")
public ResponseEntity<Object> queryAllData({} criteria, Pageable pageable){}
return new ResponseEntity<>({}.queryAllData(criteria,pageable),HttpStatus.OK);
{}
{}
""".format(
table_chinses_name,
table_chinses_name,
convert_half_camel(table_name,'_'),
convert_camel(table_name,'_'),
"{",
convert_half_camel(table_name,'_') + 'Service',
"}",
"}"
))
f_Controller.close()
#生成QueryVO
f_QueryVO=open(convert_camel(table_name,"_")+ 'QueryVO' + '.java',"a",encoding="utf-8")#利用追加模式,参数从w替换为a即可
f_QueryVO.writelines("""
package {}.vo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
import cn.com.scc.common.annotation.Query;
/**
*
* @author {}
* @date {}
**/""".format(package,author,now.strftime('%Y-%m-%d %H:%M:%S')))
f_QueryVO.writelines("""
@Data
public class {} implements Serializable{}
private static final long serialVersionUID = 1L;
""".format(convert_camel(table_name, '_') + 'QueryVO',"{"))
for index in field_values:
if('NUMBER' == index[2]):
f_QueryVO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_QueryVO.writelines(" @Query" + '\n' )
f_QueryVO.writelines(" private Long " + convert_half_camel(index[0], '_') + ';' + '\n' )
elif('VARCHAR2' == index[2]):
f_QueryVO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_QueryVO.writelines(" @Query" + '\n')
f_QueryVO.writelines(" private String " + convert_half_camel(index[0], '_') + ';' + '\n' )
else:
f_QueryVO.writelines(" " + "/**" + index[1]+ "*/" + '\n')
f_QueryVO.writelines(" @Query" + '\n')
f_QueryVO.writelines(" private Timestamp " + convert_half_camel(index[0], '_') + ';' + '\n' )
f_QueryVO.writelines("""
{}
""".format("}"))
f_QueryVO.close()
cursor.close ()
conn.close ()
def CopyFile(filepath, newPath):
# 获取当前路径下的文件名,返回List
fileNames = os.listdir(filepath)
for file in fileNames:
# 将文件命加入到当前文件路径后面
newDir = filepath + '/' + file
# 如果是文件
if os.path.isfile(newDir):
print(newDir)
newFile = newPath + '/' +file
shutil.copyfile(newDir, newFile)
#如果不是文件,递归这个文件夹的路径
else:
CopyFile(newDir,newPath)
print(tk.TkVersion)
HEIGHT = 1000
WIDTH = 1000
source_path = ''
dest_path = ''
root_window = tk.Tk()
canvas = tk.Canvas(root_window, height=HEIGHT, width=WIDTH)
canvas.pack()
frame = tk.Frame(root_window, bg='#80c1ff')
frame.place(relx=0.1, rely=0.1, relwidth= 0.8, relheight= 0.8)
# label_ip = tk.Label(frame,font=40,text='IP_host:')
# label_ip.place(relx=0.03,rely=0.15,relwidth= 0.3, relheight= 0.05)
# text1 = tk.Entry(frame,font=40)
# text1.place(relx= 0.4, rely= 0.15 ,relwidth=0.3, relheight= 0.05)
# label_port = tk.Label(frame,font=40,text='端口_PORT:')
# label_port.place(relx=0.03,rely=0.25,relwidth= 0.3, relheight= 0.05)
# text2 = tk.Entry(frame,font=40)
# text2.place(relx= 0.4, rely= 0.25 ,relwidth=0.3, relheight= 0.05)
# label_service_name = tk.Label(frame,font=40,text='服务名_SERVICE_NAME:')
# label_service_name.place(relx=0.03,rely=0.35,relwidth= 0.3, relheight= 0.05)
# text3 = tk.Entry(frame,font=40)
# text3.place(relx= 0.4, rely= 0.35 ,relwidth=0.3, relheight= 0.05)
label_table_name = tk.Label(frame,font=40,text='表名:')
label_table_name.place(relx=0.2,rely=0.25,relwidth= 0.3, relheight= 0.2)
text4 = tk.Entry(frame,font=40)
text4.place(relx= 0.6, rely= 0.25 ,relwidth=0.3, relheight= 0.2)
# label_user_name = tk.Label(frame,font=40,text='用户名:')
# label_user_name.place(relx=0.03,rely=0.55,relwidth= 0.3, relheight= 0.05)
# text5 = tk.Entry(frame,font=40)
# text5.place(relx= 0.4, rely= 0.55 ,relwidth=0.3, relheight= 0.05)
# label_password = tk.Label(frame,font=40,text='密码:')
# label_password.place(relx=0.03,rely=0.65,relwidth= 0.3, relheight= 0.05)
# text6 = tk.Entry(frame,font=40)
# text6.place(relx= 0.4, rely= 0.65 ,relwidth=0.3, relheight= 0.05)
button2 = tk.Button(frame,text="数据库测试连接",command =lambda: connect_OK())
button2.place(relx=0.3, rely= 0.8, relwidth= 0.2, relheight=0.1)
button3 = tk.Button(frame,text="确定" ,command =lambda: connect_2_oracle())
button3.place(relx=0.7, rely= 0.8, relwidth= 0.2, relheight=0.1)
root_window.title('无锡JPA代码自动生成器')
root_window.mainloop()
ORACLE-代码生成器 脚本,根据需求,可以更改定制
最新推荐文章于 2022-11-18 17:21:37 发布