Java 解析PDM 提取出建表语句

今天这篇文章是用Java来解析Power Designer 生成的.pdm文件。
先来展示几张图片

Java 解析PDM 提取出建表语句_第1张图片
Java 解析PDM 提取出建表语句_第2张图片

实现过程:

1、pom依赖


        <dependency>
            <groupId>dom4jgroupId>
            <artifactId>dom4jartifactId>
            <version>1.6.1version>
        dependency>

        
        <dependency>
            <groupId>org.fusesource.jansigroupId>
            <artifactId>jansiartifactId>
            <version>1.16version>
        dependency>

2、java代码

(图片一)

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.fusesource.jansi.Ansi;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static org.fusesource.jansi.Ansi.Color.*;

public class MainReader {

    public static void main(String[] args) throws DocumentException {
        long start = System.currentTimeMillis();

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File("D:\\doc\\物理模型设计.pdm"));
        Element rootElement = document.getRootElement();

        Namespace oNamespace = new Namespace("o", "object");
        Namespace cNamespace = new Namespace("c", "collection");
        Namespace aNamespace = new Namespace("a", "attribute");

        Element rootObject = rootElement.element(new QName("RootObject", oNamespace));

        Element children = rootObject.element(new QName("Children", cNamespace));
        Element model = children.element(new QName("Model", oNamespace));

        List<Element> tableEles = new ArrayList<>();

        //解析package
        Element packagesEle = model.element(new QName("Packages", cNamespace));
        if (packagesEle != null) {
            List<Element> packageEles = packagesEle.elements(new QName("Package", oNamespace));
            for (Element packageEle : packageEles) {
                Element tablesEle = packageEle.element(new QName("Tables", cNamespace));
                if (tablesEle != null) {
                    tableEles.addAll(tablesEle.elements(new QName("Table", oNamespace)));
                }
            }
        }


        //直接解析table
        Element tablesEle = model.element(new QName("Tables", cNamespace));
        if (tablesEle != null) {
            tableEles.addAll(tablesEle.elements(new QName("Table", oNamespace)));
        }

        System.out.println(Ansi.ansi().fg(YELLOW).a("Table size:") + Ansi.ansi().fg(Ansi.Color.GREEN).a(tableEles.size()).toString());

        System.out.println(Ansi.ansi().fgDefault().a(" "));

        int i = 0;
        for (Element tableElement : tableEles) {
            i++;
            Element name = tableElement.element(new QName("Name", aNamespace));
            Element code = tableElement.element(new QName("Code", aNamespace));
            System.out.println("------>" + Ansi.ansi().fg(BLUE).a("NO." + i) + Ansi.ansi().fg(RED).a(" " + name.getText() + " ") +
                    Ansi.ansi().fg(YELLOW).a(code.getText()) + Ansi.ansi().fgDefault().a("<-------"));

            //解析主键
            Element primaryKeyEle = tableElement.element(new QName("PrimaryKey", cNamespace));
            List<String> pkIds = new ArrayList<>();
            if (primaryKeyEle != null) {
                List<Element> pks = primaryKeyEle.elements(new QName("Key", oNamespace));
                for (Element pk1 : pks) {
                    pkIds.add(pk1.attribute("Ref").getValue());
                }
            }

            Element keysEle = tableElement.element(new QName("Keys", cNamespace));
            List<String> pkColumnIds = new ArrayList<>();
            if (keysEle != null) {
                List<Element> keyEleList = keysEle.elements(new QName("Key", oNamespace));
                for (Element keyEle : keyEleList) {
                    Attribute id = keyEle.attribute("Id");
                    if (pkIds.contains(id.getValue())) {
                        List<Element> list = keyEle.element(new QName("Key.Columns", cNamespace)).elements(new QName("Column", oNamespace));
                        for (Element element : list) {
                            pkColumnIds.add(element.attribute("Ref").getValue());
                        }
                    }
                }
            }

            //解析column
            List<Element> columns = tableElement.element(new QName("Columns", cNamespace)).elements(new QName("Column", oNamespace));
            for (Element columnEle : columns) {
                String columnId = columnEle.attribute("Id").getValue();
                Element cname = columnEle.element(new QName("Name", aNamespace));
                Element ccode = columnEle.element(new QName("Code", aNamespace));
                Element cDataType = columnEle.element(new QName("DataType", aNamespace));
                Element cLength = columnEle.element(new QName("Length", aNamespace));
                Element cComment = columnEle.element(new QName("Comment", aNamespace));
                Element nullable = columnEle.element(new QName("Column.Mandatory", aNamespace));

                System.out.print(getPadString(ccode.getText(), 20));
                System.out.print(getPadString(getTextFromEle(cDataType), 15));
                System.out.print(getPadString(getTextFromEle(cLength), 7));

                if (pkColumnIds.contains(columnId)) {
                    System.out.print("√  ");
                } else {
                    System.out.print("   ");
                }

                if (nullable != null) {
                    System.out.print("M  ");
                } else {
                    System.out.print("   ");
                }

                System.out.print(cname.getText());
                if (cComment != null) {
                    System.out.print("   (" + getTextFromEle(cComment).replace("\n", "  ") + ")");
                }
                System.out.println();
            }
            System.out.println();

        }

        System.out.println("================================");
        System.out.println("Use time:" + Ansi.ansi().fg(RED).a((System.currentTimeMillis() - start) / 1000F) + Ansi.ansi().fg(DEFAULT).a("s"));
        System.out.println();
        System.out.print(Ansi.ansi().fg(YELLOW).a("说明: "));
        System.out.print(Ansi.ansi().fg(DEFAULT).a(""));
        System.out.println("表标题分别为 列代码/类型/长度/是否为主键/是否允许为空/列可读名称及备注");
        System.out.println("      √ 表示主键, M 表示不能为空");
        System.out.println();
    }

    static String getTextFromEle(Element element) {
        if (element == null) {
            return "";
        }
        return element.getText();
    }

    /**
     * @see String#format(String, Object...)
     */
    static String getPadString(String str, int length) {
        int size = str.length();
        if (size < length) {
            str += getBlank(length - size);
            return str;
        } else
            return str + "  ";
    }


    static String getBlank(int length) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < length; i++) {
            s.append(" ");
        }
        return s.toString();
    }
}

(图片二)

import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 主键和索引
 */
public class PDMTableGeneratorPrimary {

    public static void main(String[] args) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("D:\\doc\\天源迪科\\1-安全门户物理模型设计.pdm"));
        Element root = document.getRootElement();
        Namespace oNamespace = new Namespace("o", "object");
        Namespace cNamespace = new Namespace("c", "collection");
        Namespace aNamespace = new Namespace("a", "attribute");

        Element rootObject = root.element(new QName("RootObject", oNamespace));
        Element children = rootObject.element(new QName("Children", cNamespace));
        Element model = children.element(new QName("Model", oNamespace));
        Element packages = model.element(new QName("Packages", cNamespace));

        // 处理所有Package中的表
        List<Element> tableEles = new ArrayList<>();
        if (packages != null) {
            List<Element> packageList = packages.elements(new QName("Package", oNamespace));
            for (Element packageEle : packageList) {
                Element tables = packageEle.element(new QName("Tables", cNamespace));
                if (tables != null) {
                    tableEles.addAll(tables.elements(new QName("Table", oNamespace)));
                }
            }
        }

        // 处理Model中的表
        Element tables = model.element(new QName("Tables", cNamespace));
        if (tables != null) {
            tableEles.addAll(tables.elements(new QName("Table", oNamespace)));
        }

        for (Element tableEle : tableEles) {
            String tableName = tableEle.elementText(new QName("Code", aNamespace));
            List<Element> columns = tableEle.element(new QName("Columns", cNamespace)).elements(new QName("Column", oNamespace));
            List<String> primaryKeyColumns = new ArrayList<>();
            HashMap<String, List<String>> indexColumns = new HashMap<>();
            System.out.println("CREATE TABLE `" + tableName + "` (");

            //解析主键
            Element primaryKeyEle = tableEle.element(new QName("PrimaryKey", cNamespace));
            List<String> pkIds = new ArrayList<>();
            if (primaryKeyEle != null) {
                List<Element> pks = primaryKeyEle.elements(new QName("Key", oNamespace));
                for (Element pk1 : pks) {
                    pkIds.add(pk1.attribute("Ref").getValue());
                }
            }

            Element keysEle = tableEle.element(new QName("Keys", cNamespace));
            List<String> pkColumnIds = new ArrayList<>();
            if (keysEle != null) {
                List<Element> keyEleList = keysEle.elements(new QName("Key", oNamespace));
                for (Element keyEle : keyEleList) {
                    Attribute id = keyEle.attribute("Id");
                    if (pkIds.contains(id.getValue())) {
                        List<Element> list = keyEle.element(new QName("Key.Columns", cNamespace)).elements(new QName("Column", oNamespace));
                        for (Element element : list) {
                            pkColumnIds.add(element.attribute("Ref").getValue());
                        }
                    }
                }
            }

            // 处理字段
            for (int i = 0; i < columns.size(); i++) {
                Element columnEle = columns.get(i);
                String columnId = columnEle.attribute("Id").getValue();
                String columnName = columnEle.elementText(new QName("Code", aNamespace));
                String dataType = getTextFromEle(columnEle.element(new QName("DataType", aNamespace)));
                String comment = getTextFromEle(columnEle.element(new QName("Comment", aNamespace)));
                Element nullable = columnEle.element(new QName("Mandatory", aNamespace));
                Element identity = columnEle.element(new QName("Identity", aNamespace));

                System.out.print("  `" + columnName + "` " + dataType);

                if (nullable != null) {
                    System.out.print(" NOT NULL");
                }
                else
                {
                    System.out.print(" DEFAULT NULL");
                }

                if (identity != null && identity.getText().equals("1")) {
                    System.out.print(" AUTO_INCREMENT");
                }

                if (comment != null) {
                    System.out.print(" COMMENT '" + comment + "'");
                }

                System.out.print(",");
                System.out.println();

                // 处理主键和索引
                if (pkColumnIds.contains(columnId)) {
                    primaryKeyColumns.add(columnName);
                }
            }

            // 添加主键
            if (!primaryKeyColumns.isEmpty()) {
                System.out.print("  PRIMARY KEY (");
                for (int i = 0; i < primaryKeyColumns.size(); i++) {
                    System.out.print("`" + primaryKeyColumns.get(i) + "`");
                    if (i < primaryKeyColumns.size() - 1) {
                        System.out.print(",");
                    }
                }
                System.out.print(")");
                System.out.println();
            }

            System.out.println(") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
            System.out.println();
        }
    }

    static String getTextFromEle(Element element) {
        if (element == null) {
            return "";
        }
        return element.getText();
    }
}

网上关于java解析PDM的文章确实很少,感谢这位好兄弟提供的源码参考
https://github.com/chenjazz/PdmReader

你可能感兴趣的:(工具类,java,pdm)