开发者

JSP/Struts2/Hibernate: loop through a self-referencing table

开发者 https://www.devze.com 2023-02-02 19:57 出处:网络
Let\'s say we have a self-referencing table called PERSON, with the following columns: ID, PARENT, where PARENT is a foreign key to the ID column of another element in the PERSON table. Of course, man

Let's say we have a self-referencing table called PERSON, with the following columns: ID, PARENT, where PARENT is a foreign key to the ID column of another element in the PERSON table. Of course, many persons can have the same parent.

I use Hibernate 3 in lazy fetching mode to deal with the database. Hibernate fetches a person element from the database, which is then put in the ValueStack by the Struts2 action, to be used on the result JSP page.

Now the question is : In JSP, how can I do to display all the child (and the child's child, and so on, like a family tree) of this person element?

Of course, for the n+1 children I can use the < s:iterator> tag over the person.person. I can also nest another < s:iterator> tag over person.person.person to get the n+2 children.

开发者_StackOverflow

But what if I want to do this in an automated manner, up to the last n+p child, displaying in the process all the children of all the n+1..n+p elements?

I hope I have been clear enough. Thank you all for your time.

-- TBW.


You can do this pretty easily with JSTL and a custom tag file. The idea is that the tag is recursive. Note that some early versions of WebLogic 11g had a bug that prevented recursive tags from working properly, but in general this is well supported by servlet containers and app servers.

person.tag

<%@attribute name="value" required="true" type="com.example.Person"%>

<c:forEach items="${value.children}" var="child">
    display child info...
    <z:person value="${child}"/>
</c:forEach>

(I just wrote the example from memory, it may need some slight tweaks)

Because you're lazy-loading, you'll probably want to use the Open Session in View pattern, as Quaternion mentioned (Spring not required).

0

精彩评论

暂无评论...
验证码 换一张
取 消