小白看了脚本之家有人分享代码生成器,拿来后简单修改一下分享,适合新手,自己借鉴修改,自定义代码生成器
生成器类
package config; import java.io.*; import java.sql.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.jfinal.kit.PropKit; import util.Util1; import util.UtilGenerator; /** * 代码生成工具 V2.0 */ public class MyGenerator { /** * 程序自动设置 */ private String tableName;//表名 private String tableComment;//表注释 /** * 数据连接配置 */ static String url =PropKit.use("config.txt").get("jdbcUrl"); static String username =PropKit.use("config.txt").get("user"); static String password =PropKit.use("config.txt").get("password"); static String dbName ="xxxx";//数据库名 /** * 基础路径,需要手动设置 */ String basePackage =System.getProperty("user.dir")+"\\src\\main\\java\\";//文件所在包位置,一般都在这一个位置,不需要修改 String tlfPath = System.getProperty("user.dir") + "\\src\\main\\resources\\jf\\";//模板文件位置 String beanName ="bean";//实体类-包名 String daoName ="dao2";//接口-包名 String implName ="dao2\\impl";//接口实现类-包名 String beanJF ="bean.jf";//实体类模板全名 String daoJF ="dao.jf";// String implJF ="impl.jf";// boolean b=true;//是否忽略表前缀,默认是false-去掉下划线骆驼峰显示 String tableQZ="d_";//忽略时必填-表前缀 /** * 构造参数,设置表名 */ private MyGenerator(String tableName) { //设置表名 this.tableName = tableName; } /** * 读取模板,设置内容,生成文件 * @param templatePath 模板文件路径 * @param outputFile 文件生成路径 * @param tableInfos 表字段信息 * @param customParameter 自定义参数 * @param packageName 所在的包名 */ private void writer(String templatePath, String outputFile,List<TableInfo> tableInfos,Map<String,String> customParameter,String packageName){ //主键 TableInfo prikey = new TableInfo(); //for循环标识 boolean forFlag = false; StringBuilder forContent = new StringBuilder(); //类名 String replacement =""; if(b) { replacement=UtilGenerator.ignoreTableNameQZ(tableQZ,tableName); }else { replacement=UtilGenerator.camelCaseName(tableName); } //遍历属性 for (TableInfo tableInfo : tableInfos) { //主键 if ("PRI".equals(tableInfo.getColumnKey())) { prikey = tableInfo; break; } } try(FileReader fileReader = new FileReader(templatePath);BufferedReader reader = new BufferedReader(fileReader)) { //生成文件(如果文件已经存在就不会生成,防止覆盖) if(!UtilGenerator.isFile(outputFile)) { File file = UtilGenerator.createFile(outputFile); StringBuffer stringBuffer = new StringBuffer(); //读取模板文件,拼接文件内容 Object[] lines = reader.lines().toArray(); for (Object o : lines) { String line = String.valueOf(o); /* 设置值 */ //${tableName} 表名称,例如:tb_user if(line.contains("${tableName}")){ line = line.replaceAll("\\$\\{tableName}", tableName); } //${tableComment} 表注释,例如:tb_user if(line.contains("${tableComment}")){ line = line.replaceAll("\\$\\{tableComment}", tableComment); } //${packageName} 包名称,例如:dao.impl if(line.contains("${packageName}")){ line = line.replaceAll("\\$\\{packageName}", packageName.replaceAll("\\\\", ".")); } //${entity} 实体类名称,例如:TbUser if(line.contains("${entity}")){ line = line.replaceAll("\\$\\{entity}", replacement); } //${entityFirstToLowerCase} 实体类名称首字母小写,例如:tbUser if(line.contains("${entityFirstToLowerCase}")){ line = line.replaceAll("\\$\\{entityFirstToLowerCase}",replacement); } //${entityToLowerCase} 实体类名称全小写,例如:tbuser if(line.contains("${entityToLowerCase}")){ line = line.replaceAll("\\$\\{entityToLowerCase}", replacement.toLowerCase()); } //${priDataType} 实体类主键类型,例如:String if(line.contains("${priDataType}")){ line = line.replaceAll("\\$\\{priDataType}", UtilGenerator.typeMapping(prikey.getDataType())); } //处理自定义参数 line = customParameter(line,customParameter); //先取得循环体的内容 if(forFlag){ forContent.append(line).append("\n"); } //是否为for循环遍历表字段 if(line.contains("#for")){ forFlag = true; } if(line.contains("#end")){ forFlag = false; line = line.replaceAll("#end", ""); } //遍历循环体的内容,并设置值 if(!forFlag && forContent.length() > 0){ //遍历表字段 for (TableInfo tableInfo : tableInfos) { String tableColumns = forContent.toString() //表字段信息:类型、名称、注释 .replaceAll("\\$\\{tableInfo.dataType}", UtilGenerator.typeMapping(tableInfo.getDataType())) .replaceAll("\\$\\{tableInfo.columnName}", UtilGenerator.camelCaseName(tableInfo.getColumnName())) .replaceAll("\\$\\{tableInfo.columnComment}", tableInfo.getColumnComment()); //清除多余#end,以及换行符 tableColumns = tableColumns.replaceAll("#end", "").replaceAll("\n", ""); //设置是否主键、是否自增 String pri = "",autoIncrement=""; //主键 // if ("PRI".equals(tableInfo.getColumnKey())) { // pri = " @Id\n"; // //自增id // if ("auto_increment".equals(tableInfo.getExtra())){ // autoIncrement = "@GeneratedValue(strategy= GenerationType.IDENTITY)\n"; // } // } tableColumns = tableColumns .replaceAll("#ifPri", pri) .replaceAll("#ifAutoIncrement", autoIncrement); //处理自定义参数 tableColumns = customParameter(tableColumns,customParameter); //前补tab,后补换行符 stringBuffer.append(" ").append(tableColumns.trim()).append("\n"); } //置空 forContent.setLength(0); } if(!forFlag){ stringBuffer.append(line).append("\n"); } } //写入数据到到文件中 UtilGenerator.fileWriter(file, stringBuffer); System.out.println("文件生成成功:"+outputFile); }else { System.out.println("该文件已存在:"+outputFile); } }catch (Exception e){ e.printStackTrace(); } } /** * 处理自定义参数 */ private String customParameter(String str,Map<String,String> customParameter){ for (String key : customParameter.keySet()) { str = str.replaceAll("\\$\\{"+key+"}",customParameter.get(key)); } return str; } /** * 表结构信息实体类 */ private class TableInfo { private String columnName;//字段名 private String dataType;//字段类型 private String columnComment;//字段注释 private String columnKey;//主键 private String extra;//主键类型 public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public String getColumnComment() { return columnComment; } public void setColumnComment(String columnComment) { this.columnComment = columnComment; } public String getColumnKey() { return columnKey; } public void setColumnKey(String columnKey) { this.columnKey = columnKey; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } } /** * 获取表结构信息 * 目前仅支持mysql */ private List<TableInfo> getTableInfo() { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; ArrayList<TableInfo> list = new ArrayList<>(); try { conn = UtilGenerator.getConnection(url,username,password); //表字段信息 String sql = "select column_name,data_type,column_comment,column_key,extra from information_schema.columns where table_schema = (select database()) and table_name=?"; ps = conn.prepareStatement(sql); ps.setString(1, tableName); rs = ps.executeQuery(); while (rs.next()) { TableInfo tableInfo = new TableInfo(); //列名,全部转为小写 tableInfo.setColumnName(rs.getString("column_name").toLowerCase()); //列类型 tableInfo.setDataType(rs.getString("data_type")); //列注释 tableInfo.setColumnComment(rs.getString("column_comment")); //主键 tableInfo.setColumnKey(rs.getString("column_key")); //主键类型 tableInfo.setExtra(rs.getString("extra")); list.add(tableInfo); } //表注释 sql = "select table_comment from information_schema.tables where table_schema = (select database()) and table_name=?"; ps = conn.prepareStatement(sql); ps.setString(1, tableName); rs = ps.executeQuery(); while (rs.next()) { //表注释 tableComment = rs.getString("table_comment"); } } catch (SQLException e) { e.printStackTrace(); } finally { if(rs != null){ UtilGenerator.close(conn, ps, rs); } } return list; } /** * 获取该数据库所有表名 * 目前仅支持mysql * @param name数据库名 */ private static List<String> getTableAllName(String name) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; ArrayList<String> list = new ArrayList<>(); try { conn = UtilGenerator.getConnection(url,username,password); //表字段信息 String sql = "SELECT table_name FROM information_schema.TABLES WHERE table_schema ='"+name+"'"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { list.add(rs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } finally { if(rs != null){ UtilGenerator.close(conn, ps, rs); } } return list; } /** * 创建类 */ private String create() { // System.out.println("生成路径位置:" + filePath); //获取表信息 List<TableInfo> tableInfo = getTableInfo(); //生成类名 String leiName="\\"; if(b) { leiName+=UtilGenerator.ignoreTableNameQZ(tableQZ,tableName); }else { leiName+=UtilGenerator.camelCaseName(tableName); } //自定义参数 HashMap<String, String> customParameter = new HashMap<>(); customParameter.put("author","作者:Auto Generator By 'wang'"); customParameter.put("date","生成日期:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //读取模板、生成代码 //生成bean类 writer(tlfPath+beanJF,basePackage+beanName+leiName+".java",tableInfo,customParameter,beanName); //生成接口 writer(tlfPath+daoJF,basePackage+daoName+leiName+"Dao.java",tableInfo,customParameter,daoName); //生成接口实现类 writer(tlfPath+implJF,basePackage+implName+leiName+"Impl.java",tableInfo,customParameter,implName); return tableName + " 后台代码生成完毕!"; } public static void main(String[] args) { for(String str:getTableAllName(dbName)) { String msg = new MyGenerator(str).create(); System.out.println(msg); } } }
工具类
package util; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class UtilGenerator { //代码生成器工具类 //file工具类 /** * 创建文件 * * @param pathNameAndFileName 路径跟文件名 * @return File对象 */ public static File createFile(String pathNameAndFileName) { File file = new File(pathNameAndFileName); try { //获取父目录 File fileParent = file.getParentFile(); if (!fileParent.exists()) { fileParent.mkdirs(); } //创建文件 if (!file.exists()) { file.createNewFile(); } } catch (Exception e) { file = null; System.err.println("新建文件操作出错"); e.printStackTrace(); } return file; } /** * 字符流写入文件 * @param file file对象 * @param stringBuffer 要写入的数据 */ public static void fileWriter(File file, StringBuffer stringBuffer) { //字符流 try { FileWriter resultFile = new FileWriter(file, false);//true,则追加写入 false,则覆盖写入 PrintWriter myFile = new PrintWriter(resultFile); //写入 myFile.println(stringBuffer.toString()); myFile.close(); resultFile.close(); } catch (Exception e) { System.err.println("写入操作出错"); e.printStackTrace(); } } /** * 查看文件是否存在 * path 全路径 * true存在 */ public static boolean isFile(String path) { System.out.println("判断文件是否存在-文件路径:"+path); File file=new File(path); return file.exists(); } //字符串处理工具类 /** * 数据库类型->JAVA类型 * @param dbType 数据库类型 * @return JAVA类型 */ public static String typeMapping(String dbType) { String javaType; if ("int|integer".contains(dbType)) { javaType = "Integer"; } else if ("float|double|decimal|real".contains(dbType)) { javaType = "Double"; } else if ("date|time|datetime|timestamp".contains(dbType)) { javaType = "Date"; } else { javaType = "String"; } return javaType; } /** * 驼峰转换为下划线 */ public static String underscoreName(String camelCaseName) { StringBuilder result = new StringBuilder(); if (camelCaseName != null && camelCaseName.length() > 0) { result.append(camelCaseName.substring(0, 1).toLowerCase()); for (int i = 1; i < camelCaseName.length(); i++) { char ch = camelCaseName.charAt(i); if (Character.isUpperCase(ch)) { result.append("_"); result.append(Character.toLowerCase(ch)); } else { result.append(ch); } } } return result.toString(); } /** * 表名忽略前缀,并且后面有下划线转换为驼峰 */ public static String ignoreTableNameQZ(String str,String name) { name=name.replaceAll(str, ""); return camelCaseName(name); } /** * 首字母大写 */ public static String captureName(String name) { char[] cs = name.toCharArray(); cs[0] -= 32; return String.valueOf(cs); } /** * 下划线转换为驼峰 */ public static String camelCaseName(String underscoreName) { StringBuilder result = new StringBuilder(); if (underscoreName != null && underscoreName.length() > 0) { boolean flag = false; for (int i = 0; i < underscoreName.length(); i++) { char ch = underscoreName.charAt(i); if ("_".charAt(0) == ch) { flag = true; } else { if (flag) { result.append(Character.toUpperCase(ch)); flag = false; } else { result.append(ch); } } } } return captureName(result.toString()); } //JDBC连接数据库工具类 static { // 1、加载驱动 try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 返回一个Connection连接 */ public static Connection getConnection(String url,String username,String password) { Connection conn = null; // 2、连接数据库 try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { e.printStackTrace(); } return conn; } /** * 关闭Connection,Statement连接 */ public static void close(Connection conn, Statement stmt) { try { conn.close(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭Connection,Statement,ResultSet连接 */ public static void close(Connection conn, Statement stmt, ResultSet rs) { try { close(conn, stmt); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } }
模板文件
bean.jf
package ${packageName}; import lombok.Data; /** * ${author} * ${date} */ @Data public class ${entity} { #for #ifPri #ifAutoIncrement private ${tableInfo.dataType} ${tableInfo.columnName};//${tableInfo.columnComment} #end }
dao.jf
package ${packageName}; import java.util.List; import com.jfinal.plugin.activerecord.Page; import model.${entity}; public interface ${entity}Dao { //说明:sql为where后语句,order为order by后语句 public boolean add(${entity} r); public boolean update(${entity} r); public boolean delete(String id); public Page<${entity}> page(int pageIndex,int pageSize); public Page<${entity}> page(int pageIndex,int pageSize,String order); public Page<${entity}> page(int pageIndex,int pageSize,String sql,String order); public List<${entity}> list(); public List<${entity}> list(String order); public List<${entity}> list(String sql,String order); public ${entity} get${entity}(String id); public ${entity} get${entity}2(String sql); }
impl.jf
package ${packageName}; import java.util.List; import com.jfinal.kit.StrKit; import com.jfinal.kit.TimeKit; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Page; import dao.${entity}Dao; import model.${entity}; public class ${entity}Impl implements ${entity}Dao { private ${entity} dao=new ${entity}().dao(); @Override public boolean add(${entity} p) { p.setId(StrKit.getRandomUUID()); p.setCreatetime(TimeKit.now("yyyy-MM-dd HH:mm:ss")); return p.save(); } @Override public boolean update(${entity} p) { p.setUpdatetime(TimeKit.now("yyyy-MM-dd HH:mm:ss")); return p.update(); } @Override public boolean delete(String id) { String sql="delete from ${tableName} where id=?"; return Db.delete(sql, id)>0?true:false; } @Override public Page<${entity}> page(int pageIndex,int pageSize) { return dao.paginate(pageIndex,pageSize, "select * ","from ${tableName}"); } @Override public Page<${entity}> page(int pageIndex, int pageSize, String order) { return dao.paginate(pageIndex,pageSize, "select * ","from ${tableName} order by "+order); } @Override public Page<${entity}> page(int pageIndex, int pageSize, String sql, String order) { return dao.paginate(pageIndex,pageSize, "select * ","from ${tableName} where "+sql+" order by "+order); } @Override public List<${entity}> list() { return dao.findAll(); } @Override public List<${entity}> list(String order) { return dao.find("select * from ${tableName} order by "+order); } @Override public List<${entity}> list(String sql, String order) { return dao.find("select * from ${tableName} where "+sql+" order by "+order); } @Override public ${entity} get${entity}(String id) { return dao.findById(id); } @Override public ${entity} get${entity}2(String sql) { return dao.find("select * from ${tableName} where "+sql).get(0); } }
效果图: