我使用PostgreSQL 9.0
我想在树大小下显示单位的名称
这是表 unit
中数据库中的示例od数据id_unit | id_parent | Name
UN_1 | NULL | test1
UN_2 | NULL | test2
UN_3 | UN_1 | test3
UN_4 | UN_1 | test4
UN_5 | UN_4 | test5
UN_6 | UN_7 | test6
UN_7 | UN_2 | test7
UN_8 | UN_4 | test8
UN_9 | UN_7 | test9
我希望以这种格式获取数据
UN_1
UN_3
UN_4 UN_5
UN_8
UN_2
UN_7 UN_6
UN_9
我使用java方法来完成这项工作
private List getChildrenUnitList(HttpServletRequest request,
List uniteList, String lang, String employee) throws Exception {
for (int i = 0; i < uniteList.size(); i++) {
UnitEntity unitEntity = (UnitEntity) uniteList.get(i);
UnitListEntity childreninitListEntity = getUniteList(request,
unitEntity.getId(), lang, employee);
unitEntity.getChildrenlist_unit()
.addAll(getChildrenUnitList(request,
childreninitListEntity.getUnitList(), lang, employee));
}
return uniteList;
}
public UnitListEntity getUniteList(HttpServletRequest request, String id,
String lang, String employee) throws Exception {
UnitListEntity unitListEntity = new UnitListEntity();
unitListEntity.setUnitList(unitDAO.findUnitListByIdEmployee(id, lang,
employee));
return unitListEntity;
}
这是一个sql方法
public List<UnitEntity> findUnitListByIdEmployee(String idParent, String lang, String idEmployee)
throws Exception {
String employees = "(select count(*) from employee where employee.id_unit = un.id_unit)";
SQLProperties properties = new SQLProperties();
properties.put("un.id_unit", UnitEntity.PROP_ID);
properties.put("un.name", UnitEntity.PROP_TEL_UNIT);
properties.put("un.order_unit", UnitEntity.PROP_ORDER_UNIT);
properties.put("un.id_parent", UnitEntity.PROP_ID_PARENT);
properties.put(employees, UnitEntity.PROP_EMPLOYEES, Hibernate.INTEGER);
String query = "SELECT ";
query += SQLUtils.getProperties(properties);
query += " FROM unit un";
query += " left outer join unit_lang un_lang on un.id_unit = un_lang.id_unit";
query += (" WHERE statut = '1' and un_lang.lang_unit_lang ='" + lang + "' and un.active_unit='1'");
if ((idParent != null) && !"".equals(idParent)) {
query += (" AND un.id_parent_unit = '" + idParent + "'");
} else {
query += (" AND un.id_parent_unit IS NULL");
}
query += " ORDER BY order_unit";
SQLQuery sqlQuery = this.getSession().createSQLQuery(query);
sqlQuery = SQLUtils.addScalar(sqlQuery, properties);
sqlQuery.setResultTransformer(Transformers.aliasToBean(UnitEntity.class));
List<UnitEntity> list = sqlQuery.list();
return list;
}
postgres中的我认为我应该使用递归查询,但我找不到解决方案