一文教你快速生成MySQL数据库关系图

  package com.example.demo;

  import java.io.BufferedReader;

  import java.io.IOException;

  import java.io.InputStream;

  import java.io.InputStreamReader;

  import java.nio.file.Files;

  import java.nio.file.Paths;

  import java.util.ArrayList;

  import java.util.Arrays;

  import java.util.HashMap;

  import java.util.List;

  import java.util.Map;

  import java.util.Set;

  import java.util.stream.Collectors;

  public class MysqlERGenerate {

  public static void main(String[] args) throws IOException {

  StringBuilder builder = new StringBuilder();

  // 输入从Navicat导出的表结构sql文件 将文件读取出来 放入字符串中

  InputStream is = Files.newInputStream(Paths.get("C:\Users\admin\Desktop\ddl.sql"));

  String line;

  BufferedReader reader = new BufferedReader(new InputStreamReader(is));

  line = reader.readLine();

  while (line != null) {

  builder.append(line);

  builder.append("

  ");

  line = reader.readLine();

  }

  reader.close();

  is.close();

  String sql = builder.toString();

  // 按照规律 使用CREATE TABLE进行分割 并删掉一个文件注释部分

  String[] split = sql.split("CREATE TABLE");

  List list = new ArrayList<>(Arrays.asList(split));

  list.remove(0);

  // 使用开头两个小撇号进行截取 得到表名 转为Map<表名, SQL>

  Map collect = list.stream().collect(Collectors.toMap(k -> {

  int firstIndex = k.indexOf("`");

  return k.substring(++firstIndex, k.indexOf("`", firstIndex));

  }, v -> v));

  // 需要创建外键的字段与对应的主表名称 Map<外键名, 外键主表名>

  Map foreignKey = new HashMap<>();

  foreignKey.put("ticket_no", "ticket");

  foreignKey.put("ticket_define_no", "ticket_define");

  foreignKey.put("pro_no", "pro_main");

  // 循环判断,生成外键SQL

  Set foreignKeyFields = foreignKey.keySet();

  for (String mainTableName : collect.keySet()) {

  String val = collect.get(mainTableName);

  for (String field : foreignKeyFields) {

  if (!mainTableName.equals(foreignKey.get(field)) && val.indexOf("`" + field + "`") > 0) {

  String createForeignKeySql = String.format("alter table %s add foreign key %s(%s) references %s(%s);", mainTableName, mainTableName + field + System.currentTimeMillis(), field, foreignKey.get(field), field);

  System.out.println(createForeignKeySql);

  }

  }

  }

  }

  }