Search in sources :

Example 41 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class UpdateSqlCreator method makeSQL.

private Sql makeSQL(T t, String[] fields) throws SqlCreateException {
    Sql sql = new Sql();
    Class<?> clazz = t.getClass();
    //if fields is empty
    if (fields == null || fields.length == 0) {
        fields = ORMConfigBeanUtil.getFields(clazz);
    }
    String table = ORMConfigBeanUtil.getTable(clazz, false);
    StringBuilder values = new StringBuilder();
    ReflectUtil ru = new ReflectUtil(t);
    String[] columns = ORMConfigBeanUtil.getColumns(clazz, fields);
    String idColumn = ORMConfigBeanUtil.getIdColumn(clazz);
    String idField = ORMConfigBeanUtil.getIdField(clazz);
    Method idGetter = ru.getGetter(idField);
    if (idGetter == null)
        throw new SqlCreateException("can not find id getter.");
    Object idValue = null;
    try {
        idValue = idGetter.invoke(t);
    } catch (Exception e) {
        throw new SqlCreateException(idGetter + " invoke exception " + e.toString(), e);
    }
    for (int i = 0; i < fields.length; i++) {
        String field = fields[i];
        String column = columns[i];
        Method getter = ru.getGetter(field);
        if (getter == null)
            continue;
        try {
            Object _value = getter.invoke(t);
            if (_value == null)
                continue;
            Object value = null;
            if (ClassUtil.isPojo(_value.getClass())) {
                Field f = ru.getField(field);
                OneToOne oneAnn = getter.getAnnotation(OneToOne.class);
                if (oneAnn == null)
                    oneAnn = f.getAnnotation(OneToOne.class);
                ManyToOne manyToOneAnn = null;
                if (oneAnn == null) {
                    manyToOneAnn = getter.getAnnotation(ManyToOne.class);
                    if (manyToOneAnn == null)
                        manyToOneAnn = f.getAnnotation(ManyToOne.class);
                }
                if (oneAnn != null || manyToOneAnn != null) {
                    JoinColumn joinColAnn = getter.getAnnotation(JoinColumn.class);
                    if (joinColAnn == null)
                        joinColAnn = f.getAnnotation(JoinColumn.class);
                    if (joinColAnn != null && joinColAnn.referencedColumnName().trim().length() > 0) {
                        String refCol = joinColAnn.referencedColumnName();
                        String refField = ORMConfigBeanUtil.getField(_value.getClass(), refCol);
                        ReflectUtil tarRu = new ReflectUtil(_value);
                        Method tarFKGetter = tarRu.getGetter(refField);
                        value = tarFKGetter.invoke(_value);
                    } else {
                        ReflectUtil tarRu = new ReflectUtil(_value);
                        String tarFKField = ORMConfigBeanUtil.getIdField(_value.getClass());
                        if (tarFKField != null) {
                            Method tarFKGetter = tarRu.getGetter(tarFKField);
                            value = tarFKGetter.invoke(_value);
                        }
                    }
                }
                if (value == null)
                    continue;
            } else {
                value = _value;
            }
            if (values.length() > 0)
                values.append(", ");
            //				values.append(column).append(" = '").append(value).append("'");
            values.append(column).append(" = ? ");
            sql.args.add(value);
        } catch (Exception e) {
            throw new SqlCreateException(idGetter + " invoke exception " + e.toString(), e);
        }
    }
    //		String condition = new StringBuilder().append(idColumn).append(" = ").append("'").append(idValue).append("'").toString();
    String condition = new StringBuilder().append(idColumn).append(" = ? ").toString();
    sql.args.add(idValue);
    sql.sql = String.format("UPDATE %s SET %s WHERE %s ;", table, values, condition);
    return sql;
}
Also used : Method(java.lang.reflect.Method) ManyToOne(javax.persistence.ManyToOne) ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) OneToOne(javax.persistence.OneToOne) JoinColumn(javax.persistence.JoinColumn)

Example 42 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class ManyToManyDAO method delete.

/**
	 * 多对多级联删除 
	 * 1.如果主对象不存在与数据库,不处理 
	 * 2.否则,检查当前主对象中的关联对象,如果关联对象为空,则删除所有与主对象有关的关联关系。
	 * 3.如果当前主对象中含有关联对象,则删除这些关联对象与主对象的关系
	 * 4.不会删除主对象
	 * 
	 */
public void delete() throws DAOException {
    if (this.fields == null || this.fields.size() == 0)
        return;
    // "delete from {relTable} WHERE {from} = {fromRefVal} ;"
    String format = "delete from %s WHERE %s = ? ";
    for (Field f : fields) {
        Method tarGetter = ru.getGetter(f.getName());
        if (tarGetter == null)
            continue;
        ManyToMany ann = tarGetter.getAnnotation(ManyToMany.class);
        if (ann == null) {
            ann = f.getAnnotation(ManyToMany.class);
            if (ann == null)
                continue;
        }
        JoinTable join = tarGetter.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;
        String relTable = join.name();
        String from = froms[0].name();
        String fromRefCol = froms[0].referencedColumnName();
        if (fromRefCol == null || fromRefCol.trim().length() == 0)
            fromRefCol = ORMConfigBeanUtil.getIdColumn(t);
        String fromRefField = ORMConfigBeanUtil.getField(t.getClass(), fromRefCol);
        Method fromRefFieldGetter = ru.getGetter(fromRefField);
        if (fromRefFieldGetter == null)
            throw new DAOException("can not find the 'from ref field -> " + fromRefField + "' of " + t.getClass() + " 's getter method", null);
        String fromRefVal = null;
        try {
            Object _obj = fromRefFieldGetter.invoke(t);
            if (_obj == null)
                continue;
            fromRefVal = String.valueOf(_obj);
        } catch (Exception e) {
            throw new DAOException("can not get the from ref val of " + t.getClass(), e);
        }
        List<?> tarList = null;
        try {
            tarList = (List<?>) tarGetter.invoke(t);
        } catch (Exception e) {
            throw new DAOException(tarGetter + " invoke exception, can not get the " + f.getName() + " objs ", e);
        }
        if (tarList == null || tarList.size() == 0) {
            String sql = String.format(format, relTable, from);
            // 删除所有关联记录
            DAOFactory.getUpdateDAO(dsName).updateBySQLWithArgs(sql, fromRefVal);
        } else {
            // 删除指定关联的记录
            Class<?> tarClass = ann.targetEntity();
            if (void.class.isAssignableFrom(tarClass)) {
                tarClass = ClassUtil.getGenericType(f);
            }
            String to = tos[0].name();
            String toRefCol = tos[0].referencedColumnName();
            if (toRefCol == null || toRefCol.trim().length() == 0)
                toRefCol = ORMConfigBeanUtil.getIdColumn(tarClass);
            String toRefField = ORMConfigBeanUtil.getField(tarClass, toRefCol);
            // "delete from {relTable} where {from} = {fromRefVal} and to = {toRefVal}"
            String _format = "delete from %s where %s = ? and %s = ?";
            for (int i = 0; i < tarList.size(); i++) {
                Object tarObj = tarList.get(i);
                if (tarObj == null)
                    continue;
                ReflectUtil tarRu = new ReflectUtil(tarObj);
                Method toRefFieldGetter = tarRu.getGetter(toRefField);
                if (toRefFieldGetter == null)
                    throw new DAOException("can not find the 'to ref field -> " + toRefField + "' of " + tarClass + " 's getter method", null);
                String toRefVal = null;
                try {
                    Object _obj = toRefFieldGetter.invoke(tarObj);
                    if (_obj == null)
                        continue;
                    toRefVal = String.valueOf(_obj);
                } catch (Exception e) {
                    throw new DAOException("can not get the to ref val of " + tarClass, e);
                }
                if (DAOFactory.getSelectDAO(dsName).selectOne(tarClass, new String[] { toRefField }, new String[] { toRefVal }) == null)
                    continue;
                String _sql = String.format(_format, relTable, from, to);
                DAOFactory.getUpdateDAO(dsName).updateBySQLWithArgs(_sql, fromRefVal, toRefVal);
            }
        }
    }
}
Also used : ManyToMany(javax.persistence.ManyToMany) Method(java.lang.reflect.Method) DAOException(org.eweb4j.orm.dao.DAOException) DAOException(org.eweb4j.orm.dao.DAOException) Field(java.lang.reflect.Field) ReflectUtil(org.eweb4j.util.ReflectUtil) JoinColumn(javax.persistence.JoinColumn) JoinTable(javax.persistence.JoinTable)

Example 43 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class ParamUtil method injectParam.

public static void injectParam(Context context, ReflectUtil ru, String startName) throws Exception {
    Hashtable<String, Object> hasPojo = new Hashtable<String, Object>();
    Map<String, String[]> paramMap = context.getQueryParamMap();
    paramForeach: for (Entry<String, String[]> entry : paramMap.entrySet()) {
        String paramName = entry.getKey();
        String[] paramValue = entry.getValue();
        if (paramValue == null || paramValue.length == 0)
            continue;
        Method setter = null;
        String[] pojoParamNames = paramName.split("\\.");
        if (pojoParamNames.length > 1) {
            Object lastPojo = ru.getObject();
            if (startName != null && startName.trim().length() > 0) {
                if (!pojoParamNames[0].equals(startName))
                    continue;
            }
            int lastIndex = pojoParamNames.length - 1;
            for (int i = 0; i < lastIndex; i++) {
                if (startName != null && startName.trim().length() > 0) {
                    if ((i + 1) == lastIndex)
                        break;
                    lastPojo = getLastPojo(lastPojo, pojoParamNames[i + 1], hasPojo);
                } else {
                    lastPojo = getLastPojo(lastPojo, pojoParamNames[i], hasPojo);
                }
                if (lastPojo == null)
                    continue paramForeach;
            }
            String _paramName = pojoParamNames[lastIndex];
            if (Map.class.isAssignableFrom(lastPojo.getClass())) {
                Map<String, Object> map = (HashMap<String, Object>) lastPojo;
                if (paramValue.length <= 1)
                    map.put(_paramName, paramValue[0]);
                else
                    map.put(_paramName, paramValue);
                lastPojo = map;
            }
            ReflectUtil lpRu = new ReflectUtil(lastPojo);
            setter = lpRu.getSetter(_paramName);
            if (setter == null)
                continue;
            invokeSetter(lastPojo, paramValue, setter);
        } else {
            setter = ru.getSetter(paramName);
            if (setter == null)
                continue;
            invokeSetter(ru.getObject(), paramValue, setter);
        }
    }
    injectFile(context, ru, startName);
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Entry(java.util.Map.Entry) Hashtable(java.util.Hashtable) Method(java.lang.reflect.Method) HashMap(java.util.HashMap) Map(java.util.Map)

Example 44 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class InterExecution method doIntercept.

private void doIntercept(InterConfigBean inter) throws Exception {
    Object interceptor = null;
    if ("singleton".equalsIgnoreCase(inter.getScope()))
        interceptor = SingleBeanCache.get(inter.getClazz());
    if (interceptor == null) {
        interceptor = Thread.currentThread().getContextClassLoader().loadClass(inter.getClazz()).newInstance();
        if ("singleton".equalsIgnoreCase(inter.getScope()))
            SingleBeanCache.add(inter.getClazz(), interceptor);
    }
    ReflectUtil ru = new ReflectUtil(interceptor);
    Method intercept = ru.getMethod(inter.getMethod());
    if (intercept == null) {
        this.error = null;
        return;
    }
    Method setter = ru.getSetter("Context");
    if (setter != null)
        setter.invoke(interceptor, this.context);
    Object err = null;
    Class<?>[] paramCls = intercept.getParameterTypes();
    if (paramCls.length == 1 && paramCls[0].isAssignableFrom(Context.class))
        err = intercept.invoke(interceptor, this.context);
    else
        err = intercept.invoke(interceptor);
    if (err == null) {
        this.error = null;
        return;
    }
    this.error = String.valueOf(err);
}
Also used : Context(org.eweb4j.mvc.Context) ReflectUtil(org.eweb4j.util.ReflectUtil) Method(java.lang.reflect.Method)

Example 45 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class ActionUrlUtil method pojoFieldToUrlParam.

private static void pojoFieldToUrlParam(List<String> paramNames, List<Class<?>> paramClasses, Class<?> cls) throws InstantiationException, IllegalAccessException {
    ReflectUtil _ru = new ReflectUtil(cls);
    String[] fieldNames = _ru.getFieldsName();
    Field[] fields = _ru.getFields();
    paramNames.addAll(Arrays.asList(fieldNames));
    for (java.lang.reflect.Field f : fields) {
        paramClasses.add(f.getType());
    }
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) Field(java.lang.reflect.Field)

Aggregations

ReflectUtil (org.eweb4j.util.ReflectUtil)49 Method (java.lang.reflect.Method)37 Field (java.lang.reflect.Field)26 JoinColumn (javax.persistence.JoinColumn)14 ManyToOne (javax.persistence.ManyToOne)10 ArrayList (java.util.ArrayList)9 OneToOne (javax.persistence.OneToOne)9 DAOException (org.eweb4j.orm.dao.DAOException)9 JoinTable (javax.persistence.JoinTable)7 HashMap (java.util.HashMap)6 ManyToMany (javax.persistence.ManyToMany)6 OneToMany (javax.persistence.OneToMany)6 ORMConfigBean (org.eweb4j.orm.config.bean.ORMConfigBean)6 Property (org.eweb4j.orm.config.bean.Property)6 Entry (java.util.Map.Entry)5 File (java.io.File)4 List (java.util.List)4 Map (java.util.Map)4 ConfigBean (org.eweb4j.config.bean.ConfigBean)4 Hashtable (java.util.Hashtable)3