Skip to main content

Display Multilevel Categories With Spring MVC and Hibernate

Introduction

Nowadays, I’m making a simple Content Management System using Spring MVC and Hibernate. What problems that I encountered is that I have multilevel categories which need to be queried from  database and displayed in JSP pages. After searched google, I got no idea, I don’t know if it is my problem.

The category table structure is like this:

id             cateName                parent_id

0               Java EE                      null

1               JSF                               0

2               EJB                               0

3              Facelets                        1

I want to show this in JSP page like this:

Java EE

|– JSF

|– Facelets

|– EJB

Now lets see how I solved this problem.

codes

@Override
	@Transactional(readOnly=true)
	public List getCategoryTree() {

		List parentCategories = categoryDao.getParentCategories();
		List result = new ArrayList();
		this.getCategoryTreeList(parentCategories, result, 0);

		return result;
	}

	/**
	 * recursive getting categories
	 * @param categories
	 */
	private void getCategoryTreeList(List parentCategories, List result, int depth) {
		String delemiter = "";
		if(depth > 0) {
			for(int i = 0; i < depth; i++) { delemiter += "   "; } delemiter += "|--"; } for(Category category : parentCategories) { category.setCateName(delemiter + category.getCateName()); result.add(category); if(category.getChildCategories().size() > 0) {
				getCategoryTreeList(category.getChildCategories(), result, depth + 1);
			}
		}
	}

The getCategoryTree() method is simply get categores whose parent_id is null. Because I need to modify the categories name, so we need to add @Transactional(readOnly=true) to avoid hibernate commit this modification.
getCategoryTreeList() is a recursive method which iterate top level categories to the deepest categories, and need a depth variable to generate string “|–”  with ‘nbsp;’ for html spaces. And the final result is a list that contains above information for JSP pages.

the JSP code is like this:

<c:forEach items="${categories }" var="category">
 <tr>
 <td>${category.cateName }</td>
 <td>${category.description }</td>
 <td>0</td>
 <td>
 <span class="btn-group">
 <a href="${url }/content/editCategory" title="修改" class="btn btn-small"><i class="icon-pencil"></i></a>
 <a href="${url }/content/deleteCategory" title="删除" class="btn btn-small"><i class="icon-trash"></i></a>
 </span>
 </td>
 </tr>
 </c:forEach>

conclusion

I don’t know if this is a good method. Maybe it has some performance issue, but I can’t thinking of a better way to implements this.