首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

采取Struts2,Hibernate 实现多级分类

2012-10-13 
采用Struts2,Hibernate 实现多级分类1.建持久层数据库表:表结构:category(id,name,parent_id)2.采用Hiber

采用Struts2,Hibernate 实现多级分类
1.建持久层数据库表:
表结构:category(id,name,parent_id);
2.采用Hibernate把持久的数据转化为Java对象。以便直接操纵Java对象,而不必直接操纵持久层(数据库)。
3.写一个service接口,一个service的实现类,一个service的工厂类。通过工厂类得到对应的service实现类---工厂模式。
Service接口:
public interface CatelogService{
public Category getCategoryById(Integer id, boolean withSub);

public List<Category> findCategoryByParentId(Integer catId);
}
ServiceImpl实现类:

public class CatalogServiceImpl implements CatalogService {
public Category getCategoryById(Integer id, boolean withSub) {


Session session = HibernateUtils.getSession();


Category cat = null;


if (withSub) {



Query query = session





.createQuery("select distinct c from Category c join fetch c.subCats c1 join fetch c1.subCats where c.id=?");



query.setParameter(0, 1);



List<Category> list = query.list();



if (list.size() > 0) {




cat = list.get(0);



}


} else {



cat = (Category) session.get(Category.class, id);


}


session.close();


return cat;
}

}
Service工厂类:
public class ServiceFactory {
public static CatalogService getCatalogService() {
return new CatalogServiceImpl();

}
}


4.采用Struts2框架,写一个CategoryAction,调用工厂类的静态方法getCatalogService()得到
CatalogServiceImpl对象,然后调用该对象的方法得到了Category对象。

5.在网页中取出数据:(采用EL表达式)
<c:forEach items="${cat.subCats}" var="c2">
${c2.id}
${c2.name}
<c:forEach items="${c2.subCats}" var="c3">
${c3.id}
${c3.name}
</c:forEach>
</c:forEach>

热点排行