使用hibernate实现树形结构无限级分类
在系统中,经常会用到无限级的树形结构分类,如组织机构管理、商品/地区分类等等。一般无外采用两种方式: 一是类似struts-menu(http://struts-menu.sourceforge.net)的XML文件管理方式,配置起来比较方便,但很难与系统中其它应用数据集成; 二是使用数据库存储,定义父子关系。 在我们现在开发的一个产品中,使用hibernate实现了一套树形结构的处理方法,简介如下:
由于菜单本身属于权限系统的一部分,存储在数据库中后可以方便的与部门、用户、岗位、职务等进行关联,并进行权限控制。 ■树形结构显示 ,使用的是xtree。为便于编辑维护,自己写了一个左键弹出菜单(xtree的右键事件无法更改),进行节点的添加、修改、删除、转移操作。(PS:这套维护界面是完全跨浏览器的,有兴趣的不妨一试) ■关联关系 : 可以使用objects对象来配置关联关系,实现多对多/一对多等关系。在BaseTree中,getObjects()方法是abstract的,可以根据需要自己定义。如论坛分类与每个分类所对应的贴子相关联,商品分类与商品编码相关联等,可以根据需要来处理hbm文件。若需要多项关联,亦可扩展。如菜单与用户、部门、岗位分别进行关联 ■hibernate2.1.7的一个bug ,在这个测试源码的dao中,TreeManager的getRoots方法, session.createQuery(" from " + cls.getName() + " where enabled=? and parent_id is null order by id"); 在hibernate2中必须像写成parent_id is null ,才能正确运行,这应该是2.1.7中的一个bug。而hibernate3中,可以使用parent is null的hsql。 ■主要代码 : 继承关系如下,假如要实现国家分类: CountryTree extends BaseTree(abstract class) BaseTree(abstract class) implements Tree(interface) 为节省版面,下面代码去掉了javadoc Tree.java 代码
/** * 实现了树的基本操作,上溯、下溯、子节点的添加/移除和递归查找、对象关联等 */ package test.testtree.base; import java.util.Set; public interface Tree { public String getCode(); public String getName(); public String getDescription(); public Tree getParent(); public boolean isRoot(); public boolean isLeaf(); public boolean isParentOf(Tree tree); public boolean isChildOf(Tree tree); public void addChild(Tree tree); public void rmChild(Tree tree); public Set getAllChildren(); public Set getChildren(); public Set getAllLeaves(); public void addObject(Object obj); public void rmObject(Object obj); public Set getObjects(); public Long getId(); }
BaseTree.java代码
转载于:https://www.cnblogs.com/newthing/archive/2007/10/27/2157828.html