ofbiz实体引擎(八) 创建表

    /**
     * @author 郑小康
     *
     * 1.检验实体是否为空
     *
     * 2.检验视图实体是否为空
     *
     * 3.获取数据库连接
     *
     * 4.根据对应的ModelEntity来创建表 其中modelEntities是关系表的集合
     *
     * */
    public String createTable(ModelEntity entity, Map<String, ModelEntity> modelEntities, boolean addFks) {
        if (entity == null) {
            return "ModelEntity was null and is required to create a table ModelEntity是空,不能创建表";
        }
        if (entity instanceof ModelViewEntity) {
            return "ERROR: Cannot create table for a view entity 不能为视图实体创建表";
        }

        Connection connection = null;
        Statement stmt = null;

        try {
            connection = getConnection();
        } catch (SQLException e) {
            String errMsg = "在建表过程中Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString();
            Debug.logError(e, errMsg, module);
            return errMsg;
        } catch (GenericEntityException e) {
            String errMsg = "在建表过程中 Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString();
            Debug.logError(e, errMsg, module);
            return errMsg;
        }

        StringBuilder sqlBuf = new StringBuilder("CREATE TABLE ");
        sqlBuf.append(entity.getTableName(this.datasourceInfo));
        sqlBuf.append(" (");
        Iterator<ModelField> fieldIter = entity.getFieldsIterator();
        while (fieldIter.hasNext()) {
            ModelField field = fieldIter.next();
            ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType());
            if (type == null) {
                return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table.";
            }

            sqlBuf.append(field.getColName());
            sqlBuf.append(" ");
            sqlBuf.append(type.getSqlType());

            if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) {
                // if there is a characterSet, add the CHARACTER SET arg here
                if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
                    sqlBuf.append(" CHARACTER SET ");
                    sqlBuf.append(this.datasourceInfo.getCharacterSet());
                }
                // if there is a collate, add the COLLATE arg here
                if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
                    sqlBuf.append(" COLLATE ");
                    sqlBuf.append(this.datasourceInfo.getCollate());
                }
            }

            if (field.getIsNotNull() || field.getIsPk()) {
                if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) {
                    sqlBuf.append(" CONSTRAINT NOT NULL, ");
                } else {
                    sqlBuf.append(" NOT NULL, ");
                }
            } else {
                sqlBuf.append(", ");
            }
        }

        String pkName = makePkConstraintName(entity, this.datasourceInfo.getConstraintNameClipLength());
        if (this.datasourceInfo.getUsePkConstraintNames()) {
            sqlBuf.append("CONSTRAINT ");
            sqlBuf.append(pkName);
        }
        sqlBuf.append(" PRIMARY KEY (");
        entity.colNameString(entity.getPkFieldsUnmodifiable(), sqlBuf, "");
        sqlBuf.append(")");

        if (addFks) {
            // NOTE: This is kind of a bad idea anyway since ordering table creations is crazy, if not impossible

            // go through the relationships to see if any foreign keys need to be added
            Iterator<ModelRelation> relationsIter = entity.getRelationsIterator();
            while (relationsIter.hasNext()) {
                ModelRelation modelRelation = relationsIter.next();
                if ("one".equals(modelRelation.getType())) {
                    ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName());
                    if (relModelEntity == null) {
                        Debug.logError("Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(), module);
                        continue;
                    }
                    if (relModelEntity instanceof ModelViewEntity) {
                        Debug.logError("Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(), module);
                        continue;
                    }

                    String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, this.datasourceInfo.getConstraintNameClipLength(), this.datasourceInfo.getFkStyle(), this.datasourceInfo.getUseFkInitiallyDeferred());
                    if (UtilValidate.isNotEmpty(fkConstraintClause)) {
                        sqlBuf.append(", ");
                        sqlBuf.append(fkConstraintClause);
                    } else {
                        continue;
                    }
                }
            }
        }

        sqlBuf.append(")");

        // if there is a tableType, add the TYPE arg here
        if (UtilValidate.isNotEmpty(this.datasourceInfo.getTableType())) {
         // jaz:20101229 - This appears to be only used by mysql and now mysql has
            // deprecated (and in 5.5.x removed) the use of the TYPE keyword. This is
            // changed to ENGINE which is supported starting at 4.1
            sqlBuf.append(" ENGINE ");
            //sqlBuf.append(" TYPE ");
            sqlBuf.append(this.datasourceInfo.getTableType());
        }

        // if there is a characterSet, add the CHARACTER SET arg here
        if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
            sqlBuf.append(" CHARACTER SET ");
            sqlBuf.append(this.datasourceInfo.getCharacterSet());
        }

        // if there is a collate, add the COLLATE arg here
        if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
            sqlBuf.append(" COLLATE ");
            sqlBuf.append(this.datasourceInfo.getCollate());
        }

        if (Debug.verboseOn()) Debug.logVerbose("[createTable] sql=" + sqlBuf.toString(), module);
        try {
            stmt = connection.createStatement();
            stmt.executeUpdate(sqlBuf.toString());
        } catch (SQLException e) {
            return "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString();
        } finally {
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                Debug.logError(e, module);
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                Debug.logError(e, module);
            }
        }
        return null;
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏一个会写诗的程序员的博客

6.1 Spring Boot集成mybatis6.1 Spring Boot集成mybatis

在SpringBoot集成MyBatis时,我们将去掉和Mybatis配置相关的xml文件配置方式,用注解和属性配置来代替这些繁杂的配置。

775
来自专栏何俊林

一款聚合电影、电视剧、综艺节目、动漫、游戏影音软件开源啦!

1165
来自专栏小勇DW3

SpringBoot集成mybatis配置

一个有趣的现象:传统企业大都喜欢使用hibernate,互联网行业通常使用mybatis;之所以出现这个问题感觉与对应的业务有关,比方说,互联网的业务更加的复杂...

1151
来自专栏PPV课数据科学社区

【学习】七天搞定SAS(三):基本模块调用

搞定基本的函数之后,开始鼓捣SAS里面的模型。也就是说,要开始写PROC了。说实话,越学SAS,越觉得SAS像Stata...无论是从输出的样式,还是语法。好不...

2865
来自专栏Netkiller

Mybatis 入门

Netkiller Java 手札 关于《Netkiller Java 手札》 作者2002年开始在项目中使用Java,各种原因没有留下Java文档,2015因...

2123
来自专栏Jerry的SAP技术分享

如何将S/4HANA系统存储的图片文件用Java程序保存到本地

然后我把这段代码封装到一个Function moduleZDIS_GET_MATERIAL_IMAGES里,在Java代码里消费这个function modul...

911
来自专栏积累沉淀

Hive2.0.0操作HBase 1.2.1报错解决

首先看错  org.apache.hive.service.cli.HiveSQLException: Failed to open new session: ...

1949
来自专栏菩提树下的杨过

.NET:Entity Framework 笔记

有二年没关注EF,今天无意试了下发现跟主流的Hibernate等ORM框架越来越接近了,先看下Entity类的定义: using System; using S...

1938
来自专栏IT笔记

Quartz学习笔记(四)使用druid连接池

quartz默认使用的是c3p0的连接池,记得有篇文章测试过c3p0 ,Proxool ,Druid ,Tomcat Jdbc Pool这四种连接池的性能。 大...

3435
来自专栏后端之路

SpringMvc4的Zero Xml配置

背景 相信大部分做J2ee的项目的小伙伴都会在各种配置文件中饱受摧残。听说0配置估计都蛮感兴趣。 事实上xml的配置个人觉得对于项目结构比较清晰,纯粹的java...

2285

扫码关注云+社区