我们只需要一个表就可以很好的实现无限子结点的树型目录结构了
//1.持久类实现
public class Catalog implements Serializable {
private Long id;
private Long parentId;
private String name;
private Catalog parent;
private Set children;
public Catalog() {
super();
}
/**
* @return
*/
public Set getChildren() {
return children;
}
/**
* @return
*/
public Long getId() {
return id;
}
/**
* @return
*/
public String getName() {
return name;
}
/**
* @return
*/
public Catalog getParent() {
return parent;
}
/**
* @param set
*/
public void setChildren(Set set) {
children = set;
}
/**
* @param l
*/
public void setId(Long l) {
id = l;
}
/**
* @param string
*/
public void setName(String string) {
name = string;
}
/**
* @param catalog
*/
public void setParent(Catalog catalog) {
parent = catalog;
}
public String toString() {
return new ToStringBuilder(this)
.append("customerId", getId())
.toString();
}
public boolean equals(Object other) {
if ( !(other instanceof Catalog) ) return false;
Catalog castOther = (Catalog) other;
return new EqualsBuilder()
.append(this.getId(), castOther.getId())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(getId())
.toHashCode();
}
/**
* @return
*/
public Long getParentId() {
return parentId;
}
/**
* @param long1
*/
public void setParentId(Long long1) {
parentId = long1;
}
}
//2.配置
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<!-- com.kbarol.persistence.Catalog root -->
<class name=“net.huisky.test.po.Catalog" table="catalog">
<id name="id" type="long" column="id">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="parentId" column="parent_id" type="long"/>
<set name="children"
table="catalog"
lazy="false"
>
<key column="parent_id"/>
<one-to-many class="net.huisky.test.po.Catalog"/>
</set>
<many-to-one name="parent"
insert="false"
update="false"
column="id"
class="net.huisky.test.po.Catalog"/>
</class>
</hibernate-mapping>
//3.数据库表设计
CREATE TABLE `catalog` (`id` INT (5) NOT NULL AUTO_INCREMENT, `name` VARCHAR (10) NOT NULL, `parent_id` INT (5) UNSIGNED DEFAULT '0' NOT NULL, PRIMARY KEY(`id`), UNIQUE(`id`), INDEX(`id`));
//4.相关测试代码
String hql="select catalog from Catalog as catalog where catalog.parentId=:id";
Session session=null;
List list=new ArrayList();
try {
session=super.openSession(false);
Query q=session.createQuery(hql);
q.setParameter("id",new Long(0));//查找所有根结点
list=q.list();
for(int i=0;i<parent.size();i++){
Catalog catalog=(Catalog)parent.get(i);
out.println("-"+catalog.getName()+"<br>");
Iterator it=catalog.getChildren().iterator();
while(it.hasNext()){//这里只是循环到第二层目录,可以利用递归方法再循环下去,把下面无限制级的子目录查找出来
Catalog c=(Catalog)it.next();
out.println("-----"+c.getName()+"<br>");
Iterator ii=c.getChildren().iterator();
}
}