hibernate结合json遇到的双向级联死循环
//省份表
public class Province {
private int id;
private String name;
private Set<City> cities = new HashSet<City>();
}
//市级表
public class City{
private int id;
private String name;
private Province province;
private Set<Area> areas = new HashSet<Area>();
}
//某人的地址表
public class Addresses {
private int id;
private Province province; //省份
private City city; //城市
private Area area; //地区
}
现在我想获取的是地址信息,其中包括了省份、城市两个属性,用session.createQuery();查出的address数据直接有province和city表的信息,但是用JSONArray.fromObject(ListObj);
后就会报cycle的错误,也就是死循环的错,网上找了办法说是去掉不必要的属性,但是Addresses表中的province和city等外联属性我都是需要级联取出的,这要怎么办好呢?或者推荐下好的json工具吧,感觉hibernate用json-lib很不好使。
------解决方案--------------------我来了! 在实体里面 建立一个有参构造函数,
public District(Integer id,String name) {
this.id=id;
this.name=name;
}
public Street(Integer id,String name) {
this.id = id;
this.name = name;
}
查询的时候这样,。。
/**
* 获得所有的街道
*/
@SuppressWarnings("unchecked")
public List<District> queryAll() {
Session hs = null;
List<District> listD = new ArrayList<District>();
try {
hs = HibernateSessionFactory.getSession();
String hql = "SELECT new District(d.id,d.name) from District d";
Query query = hs.createQuery(hql);
List list = query.list();
for (int i=0;i<list.size(); i++) {
District district = (District)list.get(i);
listD.add(district);
}
} catch (HibernateException e) {
e.printStackTrace();
} finally{
hs.close();
}
return listD;
}
给分哦