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