HIBERNATE JBoss.org
 |  Register  | 
     
News 
About 
   Feature List 
   Road Map 
Documentation 
   Related Projects 
   External Documentation 
Download 
Forum & Mailinglists 
Support & Training 
JIRA Issue Tracking
Wiki Community Area


Hibernate Public Training Courses


Get Hibernate in Action eBook!


JavaWorld 2003 Finalist


Jolt Award 2004 Winner
      
Documentation > Community Area > Composite Pattern

Composite Pattern

Here's an attempt at implementing the Composite Pattern using Hibernate.

http://c2.com/cgi/wiki?CompositePattern

Hibernate Mapping File

<class name="Site" table="Site">
<id name="id" type="java.lang.Integer" unsaved-value="null">
<generator class="native"/>
</id>

<version name="version" type="long"/>
<set name="childrenSites" inverse="true" lazy="true" cascade="save-update">
<key column="parent"/>
<one-to-many class="Site"/>
</set>
<many-to-one name="parent" column="parent" cascade="save-update" class="Site"/>
<property name="description" type="java.lang.String"/>
<property name="namespace" type="java.lang.String"/>
<property name="name" type="java.lang.String">
</class>

Mysql table generated by running net.sf.hibernate.tool.hbm2java.CodeGenerator.

mysql> desc site;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     |      | PRI | NULL    | auto_increment |
| version     | bigint(20)  |      |     | 0       |                |
| parent      | int(11)     | YES  | MUL | NULL    |                |
| description | varchar(64) |      |     |         |                |
| namespace   | varchar(64) |      |     |         |                |
| name        | varchar(64) |      |     |         |                |
+-------------+-------------+------+-----+---------+----------------+
6 rows in set (0.03 sec)

Code fragement showing getChildrenSites() and getParent();

List sites = session.find("FROM Site AS site");
System.out.println("Number of sites returned: " + sites.size());
Iterator iter = sites.iterator();
while (iter.hasNext()) {
Site site = (Site) iter.next();
site.getName();
site.getChildrenSites());
site.getParent();
}
      

coWiki