通过实体类生成建表SQL语句实现方法


   
   
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.lang.reflect.Field;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import org.hibernate.hql.internal.ast.SqlGenerator;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. public class Test {
  10. private static final Logger logger = LoggerFactory.getLogger(SqlGenerator.class);
  11. public static void main(String[] args) {
  12. //实体类所在的package在磁盘上的绝对路径
  13. String packageName = "d:/workspace/";
  14. //生成sql的文件夹
  15. String filePath = "I:/create/";
  16. //项目中实体类的路径
  17. String prefix = "com.zh.entity.";
  18. String className = "";
  19. StringBuffer sqls = new StringBuffer();
  20. //获取包下的所有类名称
  21. List<String> list = getAllClasses(packageName);
  22. for (String str : list) {
  23. className = prefix + str.substring( 0, str.lastIndexOf( "."));
  24. String sql = generateSql(className, filePath);
  25. sqls.append(sql);
  26. }
  27. System.out.println(sqls.toString());
  28. StringToSql(sqls.toString(), filePath + "report.sql");
  29. }
  30. /**
  31. * 根据实体类生成建表语句
  32. * @author
  33. * @date 2019年1月14日
  34. * @param className 全类名
  35. * @param filePath 磁盘路径 如 : d:/workspace/
  36. */
  37. public static String generateSql(String className,String filePath){
  38. try {
  39. Class<?> clz = Class.forName(className);
  40. className = clz.getSimpleName();
  41. Field[] fields = clz.getDeclaredFields();
  42. StringBuffer column = new StringBuffer();
  43. String varchar = " varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,";
  44. for (Field f : fields) {
  45. column.append( " \n `"+f.getName()+ "`").append(varchar);
  46. }
  47. StringBuffer sql = new StringBuffer();
  48. sql.append( "\n DROP TABLE IF EXISTS `"+className+ "`; ")
  49. .append( " \n CREATE TABLE `"+className+ "` (")
  50. .append( " \n `id` int(11) NOT NULL AUTO_INCREMENT,")
  51. .append( " \n "+column)
  52. .append( " \n PRIMARY KEY (`id`) USING BTREE,")
  53. .append( "\n INDEX `id`(`id`) USING BTREE")
  54. .append( " \n ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;");
  55. return sql.toString();
  56. } catch (ClassNotFoundException e) {
  57. logger.debug( "该类未找到!");
  58. return null;
  59. }
  60. }
  61. /**
  62. * 获取包下的所有类名称,获取的结果类似于 XXX.java
  63. * @author
  64. * @date 2019年1月14日
  65. * @param packageName
  66. * @return
  67. */
  68. public static List<String> getAllClasses(String packageName){
  69. List<String> classList = new ArrayList<String>();
  70. String className= "";
  71. File f = new File(packageName);
  72. if(f.exists() && f.isDirectory()){
  73. File[] files = f.listFiles();
  74. for (File file : files) {
  75. className = file.getName();
  76. classList.add(className);
  77. }
  78. return classList;
  79. } else{
  80. logger.debug( "包路径未找到!");
  81. return null;
  82. }
  83. }
  84. /**
  85. * 将string 写入sql文件
  86. * @author
  87. * @date 2019年1月14日
  88. * @param str
  89. * @param path
  90. */
  91. public static void StringToSql(String str,String path){
  92. byte[] sourceByte = str.getBytes();
  93. if( null != sourceByte){
  94. try {
  95. File file = new File(path); //文件路径(路径+文件名)
  96. if (!file.exists()) { //文件不存在则创建文件,先创建目录
  97. File dir = new File(file.getParent());
  98. dir.mkdirs();
  99. file.createNewFile();
  100. }
  101. FileOutputStream outStream = new FileOutputStream(file); //文件输出流用于将数据写入文件
  102. outStream.write(sourceByte);
  103. outStream.flush();
  104. outStream.close(); //关闭文件输出流
  105. System.out.println( "生成成功");
  106. } catch (Exception e) {
  107. e.printStackTrace();
  108. }
  109. }
  110. }
  111. }

生成的代码截图如下:

原文地址:https://blog.csdn.net/zgsdzczh/article/details/86487149

猜你喜欢

转载自www.cnblogs.com/jpfss/p/11358320.html