Beispiel #1
0
  /**
   * 树形结构的数据查询
   *
   * @param sql
   * @param values
   * @return
   */
  @Override
  public List<T> queryForTree(String sql, Object... values) {
    List<T> list = dao.find(sql, values);
    if (list == null || list.isEmpty()) {
      return list;
    }

    if (childCouplers.isEmpty()) {
      return list;
    }

    try {
      Method majorMethod = entityClass.getDeclaredMethod(coupler.getMajorFieldGetterName());

      StringBuffer ids = new StringBuffer();
      int i = 0;
      for (Entity entity : list) {
        ids.append(majorMethod.invoke(entity));
        if (i++ < list.size() - 1) {
          ids.append(",");
        }
      }

      for (String fieldName : oneToOneMap.keySet()) {
        OneToOne oneToOne = oneToOneMap.get(fieldName);
        String table = oneToOne.table();
        String refKey = oneToOne.foreignKey();
        parseReference(list, fieldName, majorMethod, table, refKey, ids);
      }
      for (String fieldName : oneToManyMap.keySet()) {
        OneToMany oneToMany = oneToManyMap.get(fieldName);
        String table = oneToMany.table();
        String refKey = oneToMany.foreignKey();
        parseReference(list, fieldName, majorMethod, table, refKey, ids);
      }
      for (String fieldName : manyToOneMap.keySet()) {
        ManyToOne manyToOne = manyToOneMap.get(fieldName);
        String table = manyToOne.table();
        String refKey = manyToOne.referenceKey();
        Method keyMethod =
            entityClass.getDeclaredMethod("get".concat(StringUtils.firstToUpperCase(refKey)));
        StringBuffer refIds = new StringBuffer();
        int j = 0;
        for (Entity entity : list) {
          refIds.append(keyMethod.invoke(entity));
          if (j++ < list.size() - 1) {
            refIds.append(",");
          }
        }
        parseReference(list, fieldName, keyMethod, table, refKey, refIds);
      }
    } catch (NoSuchMethodException e) {
      log.error("SimpleTreeDao.queryForTree throws NoSuchMethodException", e);
    } catch (InvocationTargetException e) {
      log.error("SimpleTreeDao.queryForTree throws InvocationTargetException", e);
    } catch (IllegalAccessException e) {
      log.error("SimpleTreeDao.queryForTree throws IllegalAccessException", e);
    } catch (NoSuchFieldException e) {
      log.error("SimpleTreeDao.queryForTree throws NoSuchFieldException", e);
    }
    return list;
  }