日期:2014-05-16  浏览次数:20325 次

json-lib hibernate 延迟加载 问题
json-lib hibernate 延迟加载 问题

------
问题:

用 json-lib 将 hibernate 延迟加载 的对象 转化为 json 时,会包 session 关闭的错误,

------
解决:

可以用 json-lib 的 JsonConfig 过滤掉 不需要的属性,利用 PropertyFilter 的 apply 方法进行过滤判断,

PropertyFilter 的 apply(Object source, String name, Object value) 方法:
* 参数:
      * source      属性所属的对象
      * name            属性的名字
      * value            属性的值
* 返回值:
      true      过滤掉
      false      保留
*

注意:
      判断 属性名 name 参数时,应当用 proxy 方式获得 Field 对象,然后再判断,不要直接用 name 判断,那样会导致延迟加载报错,

技巧:
      如果要排除1个属性,则先判断 source 的类型,然后 获得 name 对应的 Field 对象,再判断其类型,

------
例子:

* Goods.java 中排除 "GoodsType type" 属性

      /** 用于 goods 的 json config */
      public static JsonConfig jsonConfig = new JsonConfig();
      static {
            jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
                  public boolean apply(Object source, String name, Object value) {
                        if (source.getClass() == Goods.class) { // 过滤掉  Goods 中的 GoodsType
                              Field declaredField = null;
                              try {
                                    declaredField = source.getClass().getDeclaredField(name);
                              } catch (NoSuchFieldException e) {
                                    e.printStackTrace();
                              }
                              if (declaredField.getType() == GoodsType.class) {
                                    return true;
                              } else {
                                    return false;
                              }
                        } else {
                              return false;
                        }
                  }
            });
      }

------