由 Java Entity 类自动生成 SQL建表语句

网上下载的项目,有些只有代码,没有对应的数据库和sql语句。
需要自行根据Entity类来生成建表语句:

  1package com.xx;
  2
  3import java.io.File;
  4import java.io.FileOutputStream;
  5import java.lang.reflect.Field;
  6import java.util.ArrayList;
  7import java.util.HashMap;
  8import java.util.List;
  9import java.util.Map;
 10
 11import org.slf4j.Logger;
 12import org.slf4j.LoggerFactory;
 13
 14
 15/**
 16 * 根据 java 类自动生成sql 语句 - mysql
 17 */
 18public class SqlGenerator {
 19    public static Map<String, String> javaProperty2SqlColumnMap = new HashMap<>();
 20
 21    static {
 22        javaProperty2SqlColumnMap.put("Integer", "int");
 23        javaProperty2SqlColumnMap.put("Short", "tinyint(4)");
 24        javaProperty2SqlColumnMap.put("Long", "bigint");
 25        javaProperty2SqlColumnMap.put("BigDecimal", "decimal(19,2)");
 26        javaProperty2SqlColumnMap.put("Double", "double precision not null");
 27        javaProperty2SqlColumnMap.put("Float", "float");
 28        javaProperty2SqlColumnMap.put("boolean", "bit(1)");
 29        javaProperty2SqlColumnMap.put("Timestamp", "datetime");
 30        javaProperty2SqlColumnMap.put("Date", "datetime");
 31        javaProperty2SqlColumnMap.put("String", "varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL");
 32    }
 33
 34    private static final Logger logger = LoggerFactory.getLogger(SqlGenerator.class);
 35
 36    public static void main(String[] args) {
 37        //实体类所在的package在磁盘上的绝对路径
 38        String packageName = "D:\\Documents\\IdeaProjects\\xxxxxxx\\src\\main\\java\\com\\xx\\modules\\cms\\entity";
 39        //生成sql的文件夹
 40        //String filePath = "D:\\Documents\\IdeaProjects\\xxxxxxx\\";
 41        //项目中实体类的路径
 42        String prefix = "com.xx.modules.cms.entity.";
 43        String className = "";
 44
 45        StringBuffer sqls = new StringBuffer();
 46        //获取包下的所有类名称
 47        List<String> list = getAllClasses(packageName);
 48        for (String str : list) {
 49            className = prefix + str.substring(0, str.lastIndexOf("."));
 50            String sql = generateSql(className, "");
 51            sqls.append(sql);
 52        }
 53        System.out.println(sqls.toString());
 54        //StringToSql(sqls.toString(), filePath + "report.sql");
 55
 56    }
 57    /**
 58     * 根据实体类生成建表语句
 59     * @author
 60     * @date	
 61     * @param className 全类名
 62     * @param filePath 磁盘路径  如 : d:/workspace/
 63     */
 64    public static String generateSql(String className, String tableName){
 65        try {
 66            Class<?> clz = Class.forName(className);
 67            className = clz.getSimpleName();
 68            Field[] fields = clz.getDeclaredFields();
 69            String param = "";
 70            String column = "";
 71            StringBuilder sql = null;
 72            sql = new StringBuilder(50);
 73            if (tableName == null || ("").equals(tableName)) {
 74                tableName = clz.getName();
 75                tableName = tableName.substring(tableName.lastIndexOf(".") + 1);
 76            }
 77
 78            sql.append("\n\n/*========= "+tableName+" ==========*/\n");
 79            sql.append("DROP TABLE IF EXISTS `"+className+"`; \n");
 80            sql.append("CREATE TABLE `").append(tableName).append("` ( \n");
 81
 82            String keyField = "";
 83            for (Field f : fields) {
 84                column = f.getName();
 85                if (("serialVersionUID").equals(column)) {
 86                    continue;
 87                }
 88                param = f.getType().getSimpleName();
 89
 90                //将大写字母转小写,并添加下划线
 91                for (int i = 0; i < column.length(); i++) {
 92                    char c = column.charAt(i);
 93                    if (Character.isUpperCase(c) && i>0) {
 94                        column = column.replaceAll(
 95                            Character.toString(c), "_"+Character.toLowerCase(c));
 96                    }
 97                }
 98
 99                sql.append("`"+ column +"`");
100                sql.append(" ").append(javaProperty2SqlColumnMap.get(param));
101                //默认第一个是主键
102                if ("".equals(keyField)) {
103                    keyField = column;
104                }
105                sql.append(",\n");
106            }
107            sql.append("PRIMARY KEY (`"+keyField+"`) USING BTREE,");
108            sql.append("\nINDEX `"+keyField+"`(`"+keyField+"`) USING BTREE ) ");
109            sql.append("\nENGINE = INNODB DEFAULT CHARSET= utf8;");
110
111            return sql.toString();
112
113        } catch (ClassNotFoundException e) {
114            logger.debug("该类未找到!");
115            return null;
116        }
117    }
118
119    /**
120     * 获取包下的所有类名称,获取的结果类似于 XXX.java
121     * @author
122     * @date	
123     * @param packageName
124     * @return
125     */
126    public static List<String> getAllClasses(String packageName){
127        List<String> classList = new ArrayList<String>();
128        String className="";
129        File f = new File(packageName);
130        if(f.exists() && f.isDirectory()){
131            File[] files = f.listFiles();
132            for (File file : files) {
133                className = file.getName();
134                classList.add(className);
135            }
136            return classList;
137        }else{
138            logger.debug("包路径未找到!");
139            return null;
140        }
141    }
142    /**
143     * 将string 写入sql文件
144     * @author
145     * @date	
146     * @param str
147     * @param path
148     */
149    public static void StringToSql(String str,String path){
150        byte[] sourceByte = str.getBytes();
151        if(null != sourceByte){
152            try {
153                //文件路径(路径+文件名)
154                File file = new File(path);     
155                //文件不存在则创建文件,先创建目录
156                if (!file.exists()) {   
157                    File dir = new File(file.getParent());
158                    dir.mkdirs();
159                    file.createNewFile();
160                }
161                //文件输出流用于将数据写入文件
162                FileOutputStream outStream = new FileOutputStream(file);    
163                outStream.write(sourceByte);
164                outStream.flush();
165                outStream.close();  
166                System.out.println("生成成功");
167            } catch (Exception e) {
168                e.printStackTrace();
169            }
170        }
171    }
172}