示例#1
0
  private String makeSQL(T t, String[] fields, String[] values) throws SqlCreateException {
    Class<?> clazz = t.getClass();
    String table = ORMConfigBeanUtil.getTable(clazz);
    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.");

    StringBuilder condition = new StringBuilder();
    try {
      condition.append(idColumn).append(" = '").append(idGetter.invoke(t)).append("'");
    } catch (Exception e) {
      throw new SqlCreateException(idGetter + " invoke exception " + e.toString());
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < columns.length; ++i) {
      String column = columns[i];
      if (sb.length() > 0) sb.append(", ");

      sb.append(column).append(" = '");
      sb.append(values[i]).append("'");
    }

    return String.format("UPDATE %s SET %s WHERE %s ;", table, sb.toString(), condition);
  }
  private Sql makeSQL(T t, String[] fields, Object[] values) throws SqlCreateException {
    Sql sql = new Sql();
    Class<?> clazz = t.getClass();
    String table = ORMConfigBeanUtil.getTable(clazz, false);
    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);
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < columns.length; ++i) {
      String column = columns[i];
      if (sb.length() > 0) sb.append(", ");

      //			sb.append(column).append(" = '").append(values[i]).append("'");
      sb.append(column).append(" = ?");
      sql.args.add(values[i]);
    }
    //		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, sb.toString(), condition);

    return sql;
  }
  // IOC,注入对象到pojo
  private void injectIocBean() throws Exception {
    fields = ru.getFields();
    if (fields == null) return;

    for (Field f : fields) {
      Class<?> type = f.getType();

      Ioc ioc = f.getAnnotation(Ioc.class);
      if (ioc == null) continue;
      String beanId = "";
      if (ioc.value().trim().length() == 0) beanId = type.getSimpleName();
      else beanId = CommonUtil.parsePropValue(ioc.value());

      Method setter = ru.getSetter(f.getName());
      if (setter == null) continue;

      setter.invoke(this.actionObject, IOC.getBean(beanId));
    }
  }
  /** 一对多级联更新 */
  public void update(long newIdVal) {
    if (newIdVal <= 0 || this.fields == null || this.fields.size() == 0) return;
    if (this.idVal == null || "0".equals(this.idVal) || "".equals(this.idVal)) {
      return;
    } else if (DAOFactory.getSelectDAO(dsName).selectOne(t, this.idField) == null) {
      // 检查一下当前对象的ID是否存在于数据库
      return;
    }
    // "update {table} set {idCol} = {newIdVal} where {idCol} = {idVal}
    // ; update {relTable} set {fromCol} = {newIdVal} where {fromCol} = {idVal}"
    String format = "update %s set %s = %s where %s = %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;

      // 第三方关系表
      String relTable = join.name();
      // 主类在第三方关系表中的字段名
      String from = froms[0].name();

      try {
        // "update {table} set {idCol} = {newIdVal} where {idCol} = {idVal}
        // ; update {relTable} set {fromCol} = {newIdVal} where {fromCol} = {idVal}"
        final String sql1 = String.format(format, table, idColumn, newIdVal, idColumn, idVal);
        final String sql2 = String.format(format, relTable, from, newIdVal, from, idVal);
        Transaction.execute(
            new Trans() {

              @Override
              public void run(Object... args) throws Exception {
                DAOFactory.getUpdateDAO(dsName).updateBySQL(sql1);
                DAOFactory.getUpdateDAO(dsName).updateBySQL(sql2);
              }
            });

      } catch (Exception e) {
        throw new DAOException("", e);
      }
    }
  }
  public void init(Object t, List<Field> fields) throws DAOException {
    this.t = t;
    this.fields = fields;
    this.ru = new ReflectUtil(this.t);
    this.table = ORMConfigBeanUtil.getTable(this.t.getClass(), true);
    // 主类的ID属性名
    this.idField = ORMConfigBeanUtil.getIdField(this.t.getClass());
    this.idSetter = ru.getSetter(idField);
    if (this.idSetter == null) throw new DAOException("can not get idSetter.", null);

    this.idGetter = ru.getGetter(idField);
    if (this.idGetter == null) throw new DAOException("can not get idGetter.", null);

    this.idColumn = ORMConfigBeanUtil.getIdColumn(this.t.getClass());

    try {
      Object _idVal = idGetter.invoke(this.t);
      this.idVal = _idVal == null ? null : String.valueOf(_idVal);
    } catch (Exception e) {
      throw new DAOException(idGetter + " invoke exception ", e);
    }
  }
  /**
   * handle action class
   *
   * @param clsName
   * @throws Exception
   */
  public boolean handleClass(String clsName) {

    // log.debug("handleClass -> " + clsName);

    Class<?> cls = null;
    try {
      cls = Class.forName(clsName);

      if (cls == null) return false;

      String simpleName = cls.getSimpleName();
      Controller controlAnn = cls.getAnnotation(Controller.class);
      if (controlAnn == null
          && !simpleName.endsWith("Controller")
          && !simpleName.endsWith("Action")
          && !simpleName.endsWith("Control")) return false;

      String moduleName =
          CommonUtil.toLowCaseFirst(simpleName.replace("Controller", "").replace("Control", ""));
      if (simpleName.endsWith("Action")) {
        moduleName = "";
      }

      Object obj = null;
      try {
        if (cls.getAnnotation(Singleton.class) != null) {
          obj = SingleBeanCache.get(cls.getName());
          if (obj == null) {
            obj = cls.newInstance();
            SingleBeanCache.add(cls.getName(), obj);
          }
        } else obj = cls.newInstance();

      } catch (Error er) {
        // er.printStackTrace();
        log.debug("the action class new instance failued -> " + clsName + " | " + er.toString());
        return false;
      } catch (Exception e) {
        // e.printStackTrace();
        log.warn("the action class new instance failued -> " + clsName + " | " + e.toString());
        return false;
      }

      ReflectUtil ru = new ReflectUtil(obj);
      Method[] ms = ru.getMethods();
      if (ms == null) return false;

      // 扫描方法的注解信息
      for (Method m : ms) {
        if (m.getModifiers() != 1) continue;

        Path path = m.getAnnotation(Path.class);

        if (path == null) {
          String methodName = m.getName();
          Method getter = ru.getGetter(methodName.replace("get", ""));
          Method setter = ru.getSetter(methodName.replace("set", ""));
          // 默认下setter和getter不作为action方法
          if (getter != null || setter != null) continue;
        }

        handleActionConfigInfo(ru, cls, m, moduleName);
      }
    } catch (Error e) {
      return false;
    } catch (Exception e) {
      return false;
    }

    return true;
  }
 @Test
 public void test() throws Exception {
   ReflectUtil ru = new ReflectUtil(PetControl.class);
   new ActionAnnotationConfig()
       .handleActionConfigInfo(ru, PetControl.class, ru.getMethod("doHelloWorld"), "pets");
 }
  /**
   * 多对多级联查询 1.当主对象没有包含任何一个关联对象时,默认查询所有与之关联的对象 2.当主对象中包含了关联对象时(含有其id值),则只查询这些关联的对象
   *
   * @param <T>
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   * @throws IllegalArgumentException
   */
  public void select() throws DAOException {
    if (this.fields == null || this.fields.size() == 0) return;
    // select %s from {tarTable} where {referencedColumn} in (select {to} from {relTable} where
    // {from} = {idVal})
    String format = "SELECT %s FROM %s WHERE %s IN (SELECT %s FROM %s WHERE %s = ?) ";
    if (idVal == null || "0".equals(idVal) || "".equals(idVal)) return;

    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;

      // 多对多关系目标Class
      Class<?> tarClass = ann.targetEntity();
      if (void.class.isAssignableFrom(tarClass)) {
        tarClass = ClassUtil.getGenericType(f);
      }

      String tarTable = ORMConfigBeanUtil.getTable(tarClass, true);
      // 目标类对应的数据库表Id字段
      String referencedColumn = tos[0].referencedColumnName();
      if (referencedColumn == null || referencedColumn.trim().length() == 0)
        referencedColumn = ORMConfigBeanUtil.getIdColumn(tarClass);

      // 目标类在第三方关系表中的字段名
      String to = tos[0].name();

      // 第三方关系表
      String relTable = join.name();

      // 主类在第三方关系表中的字段名
      String from = froms[0].name();

      try {
        List<?> tarList = null;
        tarList = (List<?>) tarGetter.invoke(t);

        if (tarList != null && tarList.size() > 0) {
          for (int i = 0; i < tarList.size(); i++) {
            Object tarObj = tarList.get(i);
            ReflectUtil tarRu = new ReflectUtil(tarObj);
            String tarIdField = ORMConfigBeanUtil.getIdField(tarClass);
            Method tarIdGetter = tarRu.getGetter(tarIdField);
            Object tarIdValObj = tarIdGetter.invoke(tarObj);
            if (tarIdValObj == null) continue;
            String tarIdVal = String.valueOf(tarIdValObj);
            // 查询 select %s from {tarTable} where {tarIdColumn} = {tarIdVal}
            tarObj =
                DAOFactory.getSelectDAO(dsName)
                    .selectOne(tarClass, new String[] {tarIdField}, new String[] {tarIdVal});
          }
        } else {
          String sql =
              String.format(
                  format,
                  ORMConfigBeanUtil.getSelectAllColumn(tarClass),
                  tarTable,
                  referencedColumn,
                  to,
                  relTable,
                  from);
          // 从数据库中取出与当前主对象id关联的所有目标对象,
          tarList = DAOFactory.getSelectDAO(dsName).selectBySQL(tarClass, sql, idVal);
        }

        // 并注入到当前主对象的属性中
        Method tarSetter = ru.getSetter(f.getName());

        tarSetter.invoke(t, tarList);
      } catch (Exception e) {
        e.printStackTrace();
        throw new DAOException("", e);
      }
    }
  }
  /**
   * 多对多级联删除 1.如果主对象不存在与数据库,不处理 2.否则,检查当前主对象中的关联对象,如果关联对象为空,则删除所有与主对象有关的关联关系。
   * 3.如果当前主对象中含有关联对象,则删除这些关联对象与主对象的关系 4.不会删除主对象
   */
  public void delete() throws DAOException {
    if (this.fields == null || this.fields.size() == 0) return;

    // "delete from {relTable} WHERE {from} = {idVal} ;"
    String format = "delete from %s WHERE %s = ? ";
    if (idVal == null || "0".equals(idVal) || "".equals(idVal)) return;
    else if (DAOFactory.getSelectDAO(dsName).selectOne(t, this.idField) == null) return;

    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();

      List<?> tarList = null;

      try {
        tarList = (List<?>) tarGetter.invoke(t);
      } catch (Exception e) {
        throw new DAOException(tarGetter + " invoke exception ", e);
      }

      if (tarList == null || tarList.size() == 0) {
        String sql = String.format(format, relTable, from);
        // 删除所有关联记录
        DAOFactory.getUpdateDAO(dsName).updateBySQLWithArgs(sql, idVal);
      } else {
        // 删除指定关联的记录
        String to = tos[0].name();
        Class<?> tarClass = ann.targetEntity();
        if (void.class.isAssignableFrom(tarClass)) {
          tarClass = ClassUtil.getGenericType(f);
        }

        // "delete from {relTable} where {from} = {idVal} and to = {toVal}"
        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);
          String tarIdField = ORMConfigBeanUtil.getIdField(tarClass);
          Method tarIdGetter = tarRu.getGetter(tarIdField);
          Object toValObj = null;

          try {
            toValObj = tarIdGetter.invoke(tarObj);
          } catch (Exception e) {
            throw new DAOException(tarIdGetter + "invoke exception ", e);
          }

          if (toValObj == null) continue;

          String toVal = String.valueOf(toValObj);
          if (DAOFactory.getSelectDAO(dsName)
                  .selectOne(tarClass, new String[] {tarIdField}, new String[] {toVal})
              == null) continue;

          String _sql = String.format(_format, relTable, from, to);
          DAOFactory.getUpdateDAO(dsName).updateBySQLWithArgs(_sql, idVal, toVal);
        }
      }
    }
  }
  private Sql makeSQL(T t) throws SqlCreateException {
    Sql sql = new Sql();
    Class<?> clazz = t.getClass();
    String table;
    String[] columns;
    String[] fields;
    Object[] values = null;
    String idColumn;
    String idField;
    Object idValue = null;
    HashMap<String, Object> map = null;
    if (Map.class.isAssignableFrom(clazz)) {
      map = (HashMap) t;
      table = (String) map.get("table");
      idColumn = (String) map.get("idColumn");
      idField = idColumn;
      idValue = map.get("idValue");
      columns = (String[]) map.get("columns");
      fields = columns;
      values = (Object[]) map.get("values");
    } else {
      table = ORMConfigBeanUtil.getTable(clazz, false);
      columns = ORMConfigBeanUtil.getColumns(clazz);
      fields = ORMConfigBeanUtil.getFields(clazz);
      idColumn = ORMConfigBeanUtil.getIdColumn(clazz);
      idField = ORMConfigBeanUtil.getIdField(clazz);
    }

    StringBuilder valuesSb = new StringBuilder();
    ReflectUtil ru = new ReflectUtil(t);
    try {
      if (map == null) {
        Method idGetter = ru.getGetter(idField);
        if (idGetter == null) throw new SqlCreateException("can not find id getter");
        idValue = idGetter.invoke(t);
      }

      for (int i = 0; i < columns.length; i++) {
        String column = columns[i];
        String field = fields[i];
        Object value = null;
        // id 字段不允许
        if (idColumn != null && idColumn.equalsIgnoreCase(column)) continue;

        if (map != null && values != null) {
          value = values[i];
        } else {
          Method getter = ru.getGetter(field);
          if (getter == null) continue;

          Object _value = getter.invoke(t);
          if (_value == null) continue;

          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 (valuesSb.length() > 0) valuesSb.append(",");

        //				valuesSb.append(column).append(" = '").append(value).append("'");
        valuesSb.append(column).append(" = ? ");
        sql.args.add(value);
      }
    } catch (Exception e) {
      throw new SqlCreateException("" + 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, valuesSb, condition);
    return sql;
  }
  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;
  }
示例#12
0
  private String makeSQL(T t, String[] fields) throws SqlCreateException {
    Class<?> clazz = t.getClass();
    String table = ORMConfigBeanUtil.getTable(clazz);
    StringBuilder condition = new StringBuilder();
    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.");

    try {
      condition.append(idColumn).append(" = '").append(idGetter.invoke(t)).append("'");
    } catch (Exception e) {
      throw new SqlCreateException(idGetter + " invoke exception " + e.toString());
    }

    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) {
            ReflectUtil tarRu = new ReflectUtil(_value);
            String tarFKField = ORMConfigBeanUtil.getIdField(_value.getClass());

            Method tarFKGetter = tarRu.getGetter(tarFKField);
            value = tarFKGetter.invoke(_value);
          }
        }

        if (value == null) value = _value;

        if (values.length() > 0) values.append(", ");

        values.append(column).append(" = '").append(value).append("'");
      } catch (Exception e) {
        throw new SqlCreateException(idGetter + " invoke exception " + e.toString());
      }
    }

    return String.format("UPDATE %s SET %s WHERE %s ;", table, values, condition);
  }
示例#13
0
  /** 多对一级联查询 1.获取当前idVal,然后作为条件查询出其外键值,接着通过其外键值查出主对象数据,注入到当前 */
  public void select() {
    if (this.fields == null || this.fields.size() == 0) return;
    if (idVal == null || "0".equals(idVal) || "".equals(idVal)) {
      return;
    }
    //		else if (DAOFactory.getSelectDAO(dsName).selectOne(t, this.idField) == null) {
    //			// 检查一下当前对象的ID是否存在于数据库
    //			return;
    //		}

    for (Field f : fields) {
      Method tarGetter = ru.getGetter(f.getName());
      if (tarGetter == null) continue;

      String fk = null;
      OneToOne ann = tarGetter.getAnnotation(OneToOne.class);
      if (ann == null) ann = f.getAnnotation(OneToOne.class);

      if (ann == null) {
        ManyToOne moAn = tarGetter.getAnnotation(ManyToOne.class);
        if (moAn == null) moAn = f.getAnnotation(ManyToOne.class);

        if (moAn == null) continue;
      }
      String refCol = null;
      JoinColumn joinCol = f.getAnnotation(JoinColumn.class);
      if (joinCol == null) joinCol = tarGetter.getAnnotation(JoinColumn.class);

      if (joinCol == null) fk = f.getName() + "_id";
      else {
        fk = joinCol.name();
        refCol = joinCol.referencedColumnName();
      }

      Class<?> tarClass = f.getType();

      if (refCol == null || refCol.trim().length() == 0)
        refCol = ORMConfigBeanUtil.getIdColumn(tarClass);

      String refField = ORMConfigBeanUtil.getField(tarClass, refCol);

      try {
        Object _tarObj = tarGetter.invoke(t);
        Object tarObj = null;
        boolean flag = false;
        if (_tarObj != null) {
          Method refFieldGetter = new ReflectUtil(_tarObj).getGetter(refField);
          if (refFieldGetter != null && refFieldGetter.invoke(_tarObj) != null)
            tarObj = DAOFactory.getSelectDAO(dsName).selectOne(_tarObj, refField);
          else flag = true;
        } else flag = true;

        if (flag) {
          // select * from {tarTable} where {referencedColumn} = (select {fk} from {table} where
          // {idColumn} = {idVal})
          String format = "select %s from %s where %s = (select %s from %s where %s = %s )";
          String tarTable = ORMConfigBeanUtil.getTable(tarClass, true);

          String sql =
              String.format(
                  format,
                  ORMConfigBeanUtil.getSelectAllColumn(tarClass),
                  tarTable,
                  refCol,
                  fk,
                  table,
                  idColumn,
                  idVal);
          List<?> tarList = DAOFactory.getSelectDAO(dsName).selectBySQL(tarClass, sql);
          if (tarList == null || tarList.size() == 0) continue;

          tarObj = tarList.get(0);
        }

        if (tarObj == null) continue;

        Method tarSetter = ru.getSetter(f.getName());
        tarSetter.invoke(t, tarObj);
      } catch (Exception e) {
        throw new DAOException("", e);
      }
    }
  }
  private void injectActionCxt2Pojo(ReflectUtil ru) throws Exception {
    HttpServletRequest req = this.context.getRequest();
    HttpServletResponse res = this.context.getResponse();
    PrintWriter out = this.context.getWriter();
    HttpSession session = this.context.getSession();
    ActionProp actionProp = this.context.getActionProp();
    QueryParams queryParams = this.context.getQueryParams();
    for (String n : ru.getFieldsName()) {
      Method m = ru.getSetter(n);
      if (m == null) continue;

      Class<?> clazz = m.getParameterTypes()[0];
      if (Context.class.isAssignableFrom(clazz)) {
        m.invoke(ru.getObject(), this.context);
      } else if (HttpServletRequest.class.isAssignableFrom(clazz)) {
        m.invoke(ru.getObject(), req);
      } else if (HttpServletResponse.class.isAssignableFrom(clazz)) {
        m.invoke(ru.getObject(), res);
      } else if (PrintWriter.class.isAssignableFrom(clazz)) {
        m.invoke(ru.getObject(), out);
      } else if (ServletOutputStream.class.isAssignableFrom(clazz)) {
        m.invoke(ru.getObject(), this.context.getOut());
      } else if (HttpSession.class.isAssignableFrom(clazz)) {
        m.invoke(ru.getObject(), session);
      } else if (ActionProp.class.isAssignableFrom(clazz)) {
        if (actionProp == null) actionProp = new ActionProp(clazz.getName());

        this.context.setActionProp(actionProp);
        m.invoke(ru.getObject(), actionProp);
      } else if (QueryParams.class.isAssignableFrom(clazz)) {
        m.invoke(ru.getObject(), queryParams);
      } else if (Validation.class.isAssignableFrom(clazz)) {
        m.invoke(ru.getObject(), this.context.getValidation());
      } else {
        /* 如果找不到注入的类型,则尝试从IOC容器获取 */
        Object obj = IOC.getBean(n);
        if (obj != null) m.invoke(ru.getObject(), obj);
      }
    }
  }
  private void handleResult() throws Exception {

    this.exeActionLog();

    if (retn == null) return;
    String baseUrl =
        (String) this.context.getServletContext().getAttribute(MVCConfigConstant.BASE_URL_KEY);
    if (File.class.isAssignableFrom(retn.getClass())) {
      File file = (File) retn;
      this.handleDownload(file);
      return;
    } else if (File[].class.isAssignableFrom(retn.getClass())) {
      File[] files = (File[]) retn;

      String fileName = CommonUtil.getNowTime("yyyyMMddHHmmss") + "_" + "download.zip";

      HttpServletResponse resp = this.context.getResponse();
      resp.reset();
      resp.setContentType("application/zip");
      resp.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

      ServletOutputStream outputStream = resp.getOutputStream();
      ZipOutputStream zip = new ZipOutputStream(outputStream);

      for (File file : files) {
        byte[] b = new byte[1024];
        int len;
        zip.putNextEntry(new ZipEntry(file.getName()));
        FileInputStream fis = new FileInputStream(file);
        while ((len = fis.read(b)) != -1) {
          zip.write(b, 0, len);
        }

        fis.close();
      }

      zip.flush();
      zip.close();
      outputStream.flush();

      return;
    }

    if (!String.class.isAssignableFrom(retn.getClass())) {
      String mimeType = null;
      Produces prod = this.method.getAnnotation(Produces.class);
      if (prod != null && prod.value() != null && prod.value().length > 0)
        mimeType = prod.value()[0];

      if (mimeType == null || mimeType.trim().length() == 0)
        mimeType =
            this.context.getRequest().getParameter(MVCConfigConstant.HTTP_HEADER_ACCEPT_PARAM);

      if (mimeType == null || mimeType.trim().length() == 0) {
        String contentType = this.context.getRequest().getContentType();
        if (contentType != null) {
          this.context.getResponse().setContentType(contentType);
          mimeType = contentType.split(";")[0];
        }
      }

      if (this.context.getWriter() == null)
        this.context.setWriter(this.context.getResponse().getWriter());

      if (MIMEType.JSON.equals(mimeType) || "json".equalsIgnoreCase(mimeType)) {
        this.context.getResponse().setContentType(MIMEType.JSON);
        this.context.getWriter().print(CommonUtil.toJson(retn));
      } else if (MIMEType.XML.equals(mimeType) || "xml".equalsIgnoreCase(mimeType)) {
        Class<?> cls = retn.getClass();
        if (Collection.class.isAssignableFrom(cls)) {
          Class<?> _cls = ClassUtil.getPojoClass(this.method);
          if (_cls != null) cls = _cls;
        }

        XMLWriter writer = BeanXMLUtil.getBeanXMLWriter(retn);
        writer.setCheckStatck(true);
        writer.setSubNameAuto(true);
        writer.setClass(cls);
        writer.setRootElementName(null);
        this.context.getResponse().setContentType(MIMEType.XML);
        this.context.getWriter().print(writer.toXml());
      } else {
        this.context.getWriter().print("暂时不支持JSON 、XML以外的表述形式");
      }

      this.context.getWriter().flush();

      return;
    }

    List<String> produces = this.context.getActionConfigBean().getProduces();
    if (produces != null && produces.size() > 0)
      for (String produce : produces) {
        this.context.getResponse().setContentType(produce);
        break;
      }

    String re = String.valueOf(retn);

    for (Field f : fields) {
      Method getter = ru.getGetter(f.getName());
      if (getter == null) continue;

      String name = f.getName();
      if (this.context.getModel().containsKey(name)) continue;

      this.context.getModel().put(name, getter.invoke(actionObject));
    }

    this.context.getModel().put(MVCConfigConstant.BASE_URL_KEY, baseUrl);

    // 客户端重定向
    if (re.startsWith(RenderType.REDIRECT + ":")) {
      String url = re.substring((RenderType.REDIRECT + ":").length());
      String location = url;

      this.context.getResponse().sendRedirect(CommonUtil.replaceChinese2Utf8(location));

      return;
    } else if (re.startsWith(RenderType.ACTION + ":")) {
      String path = re.substring((RenderType.ACTION + ":").length());
      // ACTION 重定向
      handleActionRedirect(context, path, baseUrl);

      return;
    } else if (re.startsWith(RenderType.OUT + ":")) {
      String location = re.substring((RenderType.OUT + ":").length());
      this.context.getWriter().print(location);
      this.context.getWriter().flush();

      return;
    } else if (re.startsWith(RenderType.FORWARD + ":")) {
      String location = re.substring((RenderType.FORWARD + ":").length());
      HttpServletRequest request = this.context.getRequest();
      request.setAttribute(MVCConfigConstant.REQ_PARAM_MAP_NAME, this.context.getQueryParamMap());

      for (Iterator<Entry<String, Object>> it = this.context.getModel().entrySet().iterator();
          it.hasNext(); ) {
        Entry<String, Object> entry = it.next();
        request.setAttribute(entry.getKey(), entry.getValue());
      }

      // 服务端跳转
      request
          .getRequestDispatcher(MVCConfigConstant.FORWARD_BASE_PATH + "/" + location)
          .forward(request, this.context.getResponse());

      return;
    } else if (re.startsWith(RenderType.FREEMARKER + ":")) {
      String location = re.substring((RenderType.FREEMARKER + ":").length());
      // FreeMarker 渲染
      Configuration cfg = new Configuration();
      // 指定模板从何处加载的数据源,这里设置成一个文件目录。
      cfg.setDirectoryForTemplateLoading(
          new File(ConfigConstant.ROOT_PATH + MVCConfigConstant.FORWARD_BASE_PATH));
      // 指定模板如何检索数据模型
      cfg.setObjectWrapper(new DefaultObjectWrapper());
      cfg.setDefaultEncoding("utf-8");

      Template template = cfg.getTemplate(location);
      template.setEncoding("utf-8");

      template.process(this.context.getModel(), this.context.getWriter());

      return;
    } else if (re.startsWith(RenderType.VELOCITY + ":")) {
      String location = re.substring((RenderType.VELOCITY + ":").length());
      File viewsDir = new File(ConfigConstant.ROOT_PATH + MVCConfigConstant.FORWARD_BASE_PATH);
      // 初始化Velocity模板引擎
      Properties p = new Properties();
      p.setProperty("resource.loader", "file");
      p.setProperty(
          "file.resource.loader.class",
          "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
      p.setProperty("file.resource.loader.path", viewsDir.getAbsolutePath());
      p.setProperty("file.resource.loader.cache", "true");
      p.setProperty("file.resource.loader.modificationCheckInterval", "2");
      p.setProperty("input.encoding", "utf-8");
      p.setProperty("output.encoding", "utf-8");
      VelocityEngine ve = new VelocityEngine(p);
      // Velocity获取模板文件,得到模板引用
      org.apache.velocity.Template t = ve.getTemplate(location);
      VelocityContext velocityCtx = new VelocityContext();
      for (Iterator<Entry<String, Object>> it = this.context.getModel().entrySet().iterator();
          it.hasNext(); ) {
        Entry<String, Object> e = it.next();
        velocityCtx.put(e.getKey(), e.getValue());
      }

      // 将环境变量和输出部分结合
      t.merge(velocityCtx, this.context.getWriter());
      this.context.getWriter().flush();
      return;
    } else {
      List<ResultConfigBean> results = this.context.getActionConfigBean().getResult();

      if (results == null || results.size() == 0) {
        this.context.getWriter().print(retn);
        this.context.getWriter().flush();
        return;
      }

      boolean isOut = true;
      for (ResultConfigBean r : results) {
        if (!"_props_".equals(r.getName()) && !r.getName().equals(re) && !"".equals(re)) {
          continue;
        }

        isOut = false;
        String type = r.getType();
        String location = r.getLocation();
        if (RenderType.REDIRECT.equalsIgnoreCase(type)) {
          this.context.getResponse().sendRedirect(CommonUtil.replaceChinese2Utf8(location));

          return;
        } else if (RenderType.FORWARD.equalsIgnoreCase(type)) {
          HttpServletRequest request = this.context.getRequest();
          request.setAttribute(
              MVCConfigConstant.REQ_PARAM_MAP_NAME, this.context.getQueryParamMap());

          fields = ru.getFields();
          if (fields == null) return;

          for (Iterator<Entry<String, Object>> it = this.context.getModel().entrySet().iterator();
              it.hasNext(); ) {
            Entry<String, Object> entry = it.next();
            request.setAttribute(entry.getKey(), entry.getValue());
          }
          // 服务端跳转
          request
              .getRequestDispatcher(MVCConfigConstant.FORWARD_BASE_PATH + location)
              .forward(request, this.context.getResponse());

          return;
        } else if (RenderType.FREEMARKER.equalsIgnoreCase(type)) {
          // FreeMarker 渲染
          Configuration cfg = new Configuration();
          // 指定模板从何处加载的数据源,这里设置成一个文件目录。
          cfg.setDirectoryForTemplateLoading(
              new File(ConfigConstant.ROOT_PATH + MVCConfigConstant.FORWARD_BASE_PATH));
          // 指定模板如何检索数据模型
          cfg.setObjectWrapper(new DefaultObjectWrapper());
          cfg.setDefaultEncoding("utf-8");

          Template template = cfg.getTemplate(location);
          template.setEncoding("utf-8");

          template.process(this.context.getModel(), this.context.getWriter());

          return;
        } else if (RenderType.ACTION.equalsIgnoreCase(type)) {
          // ACTION 重定向
          handleActionRedirect(context, location, baseUrl);

          return;
        } else if (RenderType.OUT.equalsIgnoreCase(type) || location.trim().length() == 0) {
          this.context.getWriter().print(location);
          this.context.getWriter().flush();

          return;
        }
      }

      if (isOut) {
        this.context.getWriter().print(retn);
        this.context.getWriter().flush();
      }
    }
  }
  /**
   * 执行Action
   *
   * @throws Exception
   */
  public void execute() throws Exception {
    // 实例化pojo
    initPojo();

    // IOC注入对象到pojo中
    injectIocBean();

    // 注入框架mvc action 上下文环境
    this.injectActionCxt2Pojo(this.ru);

    if (IAction.class.isAssignableFrom(this.actionObject.getClass())) {
      // struts2风格
      IAction action = (IAction) actionObject;
      action.init(this.context);
      retn = action.execute();
      // 对Action执行返回结果的处理
      this.handleResult();

      return;
    }

    String methodName = this.context.getActionConfigBean().getMethod();
    Method[] methods = ru.getMethods(methodName);
    if (methods == null || methods.length == 0) return;

    method = this.getFirstMethd(methods);
    if (method == null) return;

    // 执行验证器
    this.handleValidator();
    try {
      // upload validation
      this.validateUpload();

      // 注入mvc action 请求参数
      ParamUtil.injectParam(this.context, this.ru, null);

      /* 方法体内的前置拦截器执行  */
      Before before = method.getAnnotation(Before.class);
      if (before != null) {
        InterExecution before_interExe = new InterExecution("before", context);
        before_interExe.execute(before.value());
        if (before_interExe.getError() != null) {
          before_interExe.showErr();
          return;
        }
      }

      // execute the action method
      excuteMethod(methodName);

      /* 方法体内的后置拦截器执行  */
      After after = method.getAnnotation(After.class);
      if (after != null) {
        // 后置拦截器
        InterExecution after_interExe = new InterExecution("after", context);
        after_interExe.execute(after.value());
        if (after_interExe.getError() != null) {
          after_interExe.showErr();
          return;
        }
      }

      /* 外部配置的后置拦截器后执行 */
      InterExecution after_interExe = new InterExecution("after", this.context); // 7.后置拦截器
      if (after_interExe.findAndExecuteInter()) {
        after_interExe.showErr();
        return;
      }

      // 对Action执行返回结果的处理
      this.handleResult();
    } catch (Exception e) {
      throw e;
    }
  }