Search in sources :

Example 6 with ORMConfigBean

use of org.eweb4j.orm.config.bean.ORMConfigBean in project eweb4j-framework by laiweiwei.

the class ORMConfigBeanWriter method write.

/**
	 * 将某个Class写入到目标xml文件中
	 * 
	 * @param filePath
	 *            文件相对路径
	 * @param clazzs
	 * @return
	 */
public static String write(String filePath, Class<?>... clazzs) {
    String error = null;
    File file = new File(ConfigConstant.CONFIG_BASE_PATH + filePath);
    if (filePath != null && clazzs != null && clazzs.length > 0) {
        List<ORMConfigBean> ormList = new ArrayList<ORMConfigBean>();
        try {
            for (int i = 0; i < clazzs.length; ++i) {
                Class<?> clazz = clazzs[i];
                String clsName = clazz.getSimpleName();
                Entity entity = clazz.getAnnotation(Entity.class);
                if (entity == null && !clsName.endsWith("PO") && !clsName.endsWith("POJO") && !clsName.endsWith("Entity") && !clsName.endsWith("Model")) {
                    return null;
                }
                Table tableAnn = clazz.getAnnotation(Table.class);
                String table = tableAnn == null ? "" : tableAnn.name();
                table = "".equals(table.trim()) ? clsName : table;
                ORMConfigBean ormBean = new ORMConfigBean();
                ormBean.setClazz(clazz.getName());
                ormBean.setId(clazz.getSimpleName());
                ormBean.setTable(table);
                ReflectUtil ru;
                ru = new ReflectUtil(clazz);
                List<Property> pList = new ArrayList<Property>();
                for (Field f : ru.getFields()) {
                    String name = f.getName();
                    Method getter = ru.getGetter(name);
                    Column colAnn = getter.getAnnotation(Column.class);
                    if (colAnn == null) {
                        colAnn = f.getAnnotation(Column.class);
                        if (colAnn == null)
                            continue;
                    }
                    Id idAnn = f.getAnnotation(Id.class);
                    if (idAnn == null) {
                        idAnn = getter.getAnnotation(Id.class);
                        if (idAnn == null)
                            continue;
                    }
                    Property p = new Property();
                    p.setAutoIncrement("1");
                    p.setPk("1");
                    Pk pkAnn = f.getAnnotation(Pk.class);
                    if (pkAnn != null) {
                        p.setPk("1");
                    }
                    String column = colAnn.name();
                    column = "".equals(column.trim()) ? name : column;
                    p.setName(name);
                    p.setColumn(column);
                    p.setType(f.getType().getName());
                    pList.add(p);
                }
                ormBean.setProperty(pList);
                ormList.add(ormBean);
            }
            BeanXMLUtil.getBeanXMLWriter(file, ormList).write();
        } catch (Exception e) {
            error = e.getMessage();
            e.printStackTrace();
        }
    } else {
        error = "Class参数不能为空";
    }
    return error;
}
Also used : Entity(javax.persistence.Entity) Table(javax.persistence.Table) ORMConfigBean(org.eweb4j.orm.config.bean.ORMConfigBean) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) Column(javax.persistence.Column) Id(javax.persistence.Id) Pk(org.eweb4j.orm.annotation.Pk) File(java.io.File) Property(org.eweb4j.orm.config.bean.Property)

Example 7 with ORMConfigBean

use of org.eweb4j.orm.config.bean.ORMConfigBean in project eweb4j-framework by laiweiwei.

the class PojoAnnotationConfig method onOk.

@Override
protected void onOk() throws Exception {
    for (Iterator<Entry<Object, ORMConfigBean>> it = ORMConfigBeanCache.entrySet().iterator(); it.hasNext(); ) {
        Entry<Object, ORMConfigBean> e = it.next();
        ORMConfigBean orm = e.getValue();
        Class<?> clazz = null;
        ReflectUtil ru = null;
        for (Property p : orm.getProperty()) {
            String type = p.getType();
            if (!PropType.ONE_ONE.equals(type) && !PropType.MANY_ONE.equals(type))
                continue;
            if (p.getRelProperty() != null && p.getRelProperty().trim().length() > 0)
                continue;
            if (clazz == null)
                clazz = Thread.currentThread().getContextClassLoader().loadClass(orm.getClazz());
            if (ru == null)
                ru = new ReflectUtil(clazz);
            Field f = ru.getField(p.getName());
            String refCol = ORMConfigBeanUtil.getIdColumn(f.getType());
            p.setRelProperty(ORMConfigBeanUtil.getField(f.getType(), refCol));
        }
    }
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) Entry(java.util.Map.Entry) ORMConfigBean(org.eweb4j.orm.config.bean.ORMConfigBean) Property(org.eweb4j.orm.config.bean.Property)

Example 8 with ORMConfigBean

use of org.eweb4j.orm.config.bean.ORMConfigBean in project eweb4j-framework by laiweiwei.

the class Model2Table method generateOne.

public static String generateOne(final Class<?> entityClass, final boolean isDrop, boolean isCreateFile) {
    StringBuilder sql = new StringBuilder();
    StringBuilder manyMany = new StringBuilder();
    final ORMConfigBean ocb = ORMConfigBeanCache.get(entityClass.getName());
    final String table = ocb.getTable();
    List<Property> properties = ocb.getProperty();
    StringBuilder sb = new StringBuilder();
    StringBuilder fkSb = new StringBuilder();
    final String fk = ", \n\tKEY %s (%s), \n\tCONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)";
    StringBuilder pkSb = new StringBuilder();
    final String pk = ", \n\tPRIMARY KEY (%s)";
    StringBuilder uniqueSb = new StringBuilder();
    String unique = ", \n\tUNIQUE KEY %s (%s)";
    final String idCol = ORMConfigBeanUtil.getIdColumn(properties);
    for (Property p : properties) {
        if (sb.length() > 0)
            sb.append(", \n");
        String col = p.getColumn();
        String type = p.getType();
        String size = null;
        if (p.getSize().trim().length() > 0 && CommonUtil.isNumeric(p.getSize().trim()))
            size = String.format(" (%s) ", p.getSize());
        if ("1".equals(p.getUnique()) || "true".equalsIgnoreCase(p.getUnique()))
            uniqueSb.append(String.format(unique, col, col));
        String notNull = "";
        if ("1".equals(p.getNotNull()) || "true".equalsIgnoreCase(p.getNotNull()))
            notNull = " NOT NULL ";
        if ("1".equals(p.getPk()) || "true".equalsIgnoreCase(p.getPk())) {
            if (pkSb.length() > 0)
                pkSb.append(",");
            pkSb.append(col);
        }
        String auto = "";
        if ("1".equals(p.getAutoIncrement()) || "true".equalsIgnoreCase(p.getAutoIncrement()))
            auto = " AUTO_INCREMENT ";
        if (PropType.ONE_ONE.equals(p.getType()) || PropType.MANY_ONE.equals(p.getType())) {
            final String relTable = ORMConfigBeanUtil.getTable(p.getRelClass(), false);
            if (p.getRelProperty() == null || p.getRelProperty().trim().length() == 0)
                p.setRelProperty(ORMConfigBeanUtil.getIdField(p.getRelClass()));
            final String relColumn = ORMConfigBeanUtil.getColumn(p.getRelClass(), p.getRelProperty());
            fkSb.append(String.format(fk, col, col, table + "_" + col, col, relTable, relColumn));
        }
        sb.append("\t").append(col).append(" ").append(getType(type)).append(size == null ? "" : size).append(notNull).append(auto);
    }
    sb.append(uniqueSb.toString());
    if (pkSb.length() > 0)
        sb.append(String.format(pk, pkSb.toString()));
    sb.append(fkSb.toString());
    String _sql = String.format(create_table_script, table, sb.toString());
    if (isDrop) {
        _sql = String.format(drop_table_script, table) + _sql;
        ;
    }
    sql.append(_sql);
    try {
        ReflectUtil ru = new ReflectUtil(entityClass);
        for (Field f : ru.getFields()) {
            if (!ClassUtil.isListClass(f))
                continue;
            String name = f.getName();
            Method getter = ru.getGetter(name);
            if (getter == null)
                continue;
            ManyToMany mmAnn = getter.getAnnotation(ManyToMany.class);
            if (mmAnn == null)
                mmAnn = f.getAnnotation(ManyToMany.class);
            if (mmAnn != null) {
                JoinTable join = getter.getAnnotation(JoinTable.class);
                if (join == null) {
                    join = f.getAnnotation(JoinTable.class);
                    if (join == null)
                        continue;
                }
                JoinColumn[] froms = join.joinColumns();
                if (froms == null || froms.length == 0)
                    continue;
                JoinColumn[] tos = join.inverseJoinColumns();
                if (tos == null || tos.length == 0)
                    continue;
                final String relTable = join.name();
                final String relFrom = froms[0].name();
                final String relTo = tos[0].name();
                final Class<?> targetClass = ClassUtil.getGenericType(f);
                StringBuilder manyManyField = new StringBuilder();
                //handle the many to many 
                manyManyField.append("\tid ").append(getType("long")).append(" (20) NOT NULL AUTO_INCREMENT,");
                manyManyField.append("\n\t").append(relFrom).append(" ").append(getType("long")).append(" (20) ,");
                manyManyField.append("\n\t").append(relTo).append(" ").append(getType("long")).append(" (20) ,");
                manyManyField.append("\n\t").append("PRIMARY KEY (id)");
                String tarTable = ORMConfigBeanUtil.getTable(targetClass, false);
                String tarIdCol = ORMConfigBeanUtil.getIdColumn(targetClass);
                String fk1 = String.format(fk, relFrom, relFrom, relTable + "_" + relFrom, relFrom, table, idCol);
                manyManyField.append(fk1);
                String fk2 = String.format(fk, relTo, relTo, relTable + "_" + relTo, relTo, tarTable, tarIdCol);
                manyManyField.append(fk2);
                manyMany.append(String.format(create_table_script, relTable, relTable, manyManyField.toString()));
            }
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    sql.append(manyMany.toString());
    String script = String.format("SET FOREIGN_KEY_CHECKS=0;\n%s", sql.toString());
    if (!isCreateFile)
        return script;
    try {
        ConfigBean cb = (ConfigBean) SingleBeanCache.get(ConfigBean.class.getName());
        File file = new File(ConfigConstant.CONFIG_BASE_PATH() + cb.getOrm().getDdl().getDs() + "-create.sql");
        FileWriter writer = new FileWriter(file);
        writer.write(script);
        writer.flush();
        writer.close();
        LogFactory.getORMLogger(Model2Table.class).debug("create models sql script file success -> " + file.getAbsoluteFile());
        return script;
    } catch (IOException e2) {
        e2.printStackTrace();
        return null;
    }
}
Also used : ORMConfigBean(org.eweb4j.orm.config.bean.ORMConfigBean) FileWriter(java.io.FileWriter) ManyToMany(javax.persistence.ManyToMany) Method(java.lang.reflect.Method) ORMConfigBean(org.eweb4j.orm.config.bean.ORMConfigBean) ConfigBean(org.eweb4j.config.bean.ConfigBean) IOException(java.io.IOException) IOException(java.io.IOException) ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) JoinColumn(javax.persistence.JoinColumn) Property(org.eweb4j.orm.config.bean.Property) File(java.io.File) JoinTable(javax.persistence.JoinTable)

Example 9 with ORMConfigBean

use of org.eweb4j.orm.config.bean.ORMConfigBean in project eweb4j-framework by laiweiwei.

the class Model2Table method generateAll.

public static String generateAll(final boolean isDrop, final boolean isCreateFile) {
    StringBuilder sql = new StringBuilder();
    StringBuilder manyMany = new StringBuilder();
    for (Iterator<Entry<Object, ORMConfigBean>> it = ORMConfigBeanCache.entrySet().iterator(); it.hasNext(); ) {
        final Entry<Object, ORMConfigBean> e = it.next();
        final ORMConfigBean ocb = e.getValue();
        final String table = ocb.getTable();
        List<Property> properties = ocb.getProperty();
        StringBuilder sb = new StringBuilder();
        StringBuilder fkSb = new StringBuilder();
        final String fk = ", \n\tKEY %s (%s), \n\tCONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)";
        StringBuilder pkSb = new StringBuilder();
        final String pk = ", \n\tPRIMARY KEY (%s)";
        StringBuilder uniqueSb = new StringBuilder();
        String unique = ", \n\tUNIQUE KEY %s (%s)";
        final String idCol = ORMConfigBeanUtil.getIdColumn(properties);
        for (Property p : properties) {
            if (sb.length() > 0)
                sb.append(", \n");
            String col = p.getColumn();
            String type = p.getType();
            String size = null;
            if (p.getSize().trim().length() > 0 && CommonUtil.isNumeric(p.getSize().trim()))
                size = String.format(" (%s) ", p.getSize());
            if ("1".equals(p.getUnique()) || "true".equalsIgnoreCase(p.getUnique()))
                uniqueSb.append(String.format(unique, col, col));
            String notNull = "";
            if ("1".equals(p.getNotNull()) || "true".equalsIgnoreCase(p.getNotNull()))
                notNull = " NOT NULL ";
            if ("1".equals(p.getPk()) || "true".equalsIgnoreCase(p.getPk())) {
                if (pkSb.length() > 0)
                    pkSb.append(",");
                pkSb.append(col);
            }
            String auto = "";
            if ("1".equals(p.getAutoIncrement()) || "true".equalsIgnoreCase(p.getAutoIncrement()))
                auto = " AUTO_INCREMENT ";
            if (PropType.ONE_ONE.equals(p.getType()) || PropType.MANY_ONE.equals(p.getType())) {
                final String relTable = ORMConfigBeanUtil.getTable(p.getRelClass(), false);
                if (p.getRelProperty() == null || p.getRelProperty().trim().length() == 0)
                    p.setRelProperty(ORMConfigBeanUtil.getIdField(p.getRelClass()));
                final String relColumn = ORMConfigBeanUtil.getColumn(p.getRelClass(), p.getRelProperty());
                fkSb.append(String.format(fk, col, col, table + "_" + col, col, relTable, relColumn));
            }
            sb.append("\t").append(col).append(" ").append(getType(type)).append(size == null ? "" : size).append(notNull).append(auto);
        }
        sb.append(uniqueSb.toString());
        if (pkSb.length() > 0)
            sb.append(String.format(pk, pkSb.toString()));
        sb.append(fkSb.toString());
        String _sql = String.format(create_table_script, table, sb.toString());
        if (isDrop) {
            _sql = String.format(drop_table_script, table) + _sql;
            ;
        }
        sql.append(_sql);
        try {
            Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass((String) e.getKey());
            ReflectUtil ru = new ReflectUtil(clazz);
            for (Field f : ru.getFields()) {
                if (!ClassUtil.isListClass(f))
                    continue;
                String name = f.getName();
                Method getter = ru.getGetter(name);
                if (getter == null)
                    continue;
                ManyToMany mmAnn = getter.getAnnotation(ManyToMany.class);
                if (mmAnn == null)
                    mmAnn = f.getAnnotation(ManyToMany.class);
                if (mmAnn != null) {
                    JoinTable join = getter.getAnnotation(JoinTable.class);
                    if (join == null) {
                        join = f.getAnnotation(JoinTable.class);
                        if (join == null)
                            continue;
                    }
                    JoinColumn[] froms = join.joinColumns();
                    if (froms == null || froms.length == 0)
                        continue;
                    JoinColumn[] tos = join.inverseJoinColumns();
                    if (tos == null || tos.length == 0)
                        continue;
                    final String relTable = join.name();
                    final String relFrom = froms[0].name();
                    final String relTo = tos[0].name();
                    final Class<?> targetClass = ClassUtil.getGenericType(f);
                    StringBuilder manyManyField = new StringBuilder();
                    //handle the many to many 
                    manyManyField.append("\tid ").append(getType("long")).append(" (20) NOT NULL AUTO_INCREMENT,");
                    manyManyField.append("\n\t").append(relFrom).append(" ").append(getType("long")).append(" (20) ,");
                    manyManyField.append("\n\t").append(relTo).append(" ").append(getType("long")).append(" (20) ,");
                    manyManyField.append("\n\t").append("PRIMARY KEY (id)");
                    String tarTable = ORMConfigBeanUtil.getTable(targetClass, false);
                    String tarIdCol = ORMConfigBeanUtil.getIdColumn(targetClass);
                    String fk1 = String.format(fk, relFrom, relFrom, relTable + "_" + relFrom, relFrom, table, idCol);
                    manyManyField.append(fk1);
                    String fk2 = String.format(fk, relTo, relTo, relTable + "_" + relTo, relTo, tarTable, tarIdCol);
                    manyManyField.append(fk2);
                    manyMany.append(String.format(create_table_script, relTable, relTable, manyManyField.toString()));
                }
            }
        } catch (Exception e1) {
            continue;
        }
    }
    sql.append(manyMany.toString());
    String script = String.format("SET FOREIGN_KEY_CHECKS=0;\n%s", sql.toString());
    if (!isCreateFile)
        return script;
    try {
        ConfigBean cb = (ConfigBean) SingleBeanCache.get(ConfigBean.class.getName());
        File file = new File(ConfigConstant.CONFIG_BASE_PATH() + cb.getOrm().getDdl().getDs() + "-create.sql");
        FileWriter writer = new FileWriter(file);
        writer.write(script);
        writer.flush();
        writer.close();
        LogFactory.getORMLogger(Model2Table.class).debug("create models sql script file success -> " + file.getAbsoluteFile());
        return script;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Also used : ORMConfigBean(org.eweb4j.orm.config.bean.ORMConfigBean) FileWriter(java.io.FileWriter) ManyToMany(javax.persistence.ManyToMany) Method(java.lang.reflect.Method) ORMConfigBean(org.eweb4j.orm.config.bean.ORMConfigBean) ConfigBean(org.eweb4j.config.bean.ConfigBean) IOException(java.io.IOException) IOException(java.io.IOException) ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) Entry(java.util.Map.Entry) JoinColumn(javax.persistence.JoinColumn) Property(org.eweb4j.orm.config.bean.Property) File(java.io.File) JoinTable(javax.persistence.JoinTable)

Example 10 with ORMConfigBean

use of org.eweb4j.orm.config.bean.ORMConfigBean in project eweb4j-framework by laiweiwei.

the class DeleteSqlCreator method makeSQL.

private Sql makeSQL(T t, String condition) {
    Sql sql = new Sql();
    ORMConfigBean ormBean = ORMConfigBeanCache.get(t.getClass().getName());
    String table = ormBean != null ? ormBean.getTable() : t.getClass().getSimpleName();
    sql.sql = String.format("DELETE FROM %s WHERE %s ;", table, condition);
    return sql;
}
Also used : ORMConfigBean(org.eweb4j.orm.config.bean.ORMConfigBean)

Aggregations

ORMConfigBean (org.eweb4j.orm.config.bean.ORMConfigBean)16 Property (org.eweb4j.orm.config.bean.Property)11 Field (java.lang.reflect.Field)6 ArrayList (java.util.ArrayList)6 ConfigBean (org.eweb4j.config.bean.ConfigBean)5 ReflectUtil (org.eweb4j.util.ReflectUtil)5 File (java.io.File)4 Method (java.lang.reflect.Method)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Entry (java.util.Map.Entry)3 JoinColumn (javax.persistence.JoinColumn)3 FileWriter (java.io.FileWriter)2 IOException (java.io.IOException)2 Column (javax.persistence.Column)2 Entity (javax.persistence.Entity)2 JoinTable (javax.persistence.JoinTable)2 ManyToMany (javax.persistence.ManyToMany)2 Table (javax.persistence.Table)2 LogConfigBean (org.eweb4j.config.bean.LogConfigBean)2