File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes how to map composite objects to database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to map composite objects to database" Watch "how to map composite objects to database" New topic

how to map composite objects to database

richard chang

Joined: Apr 05, 2004
Posts: 3
I'm new to design patterns. Just read composite pattern which is good at handling recurive data. But I don't know how to map composite objects to database? For example, an Folder object composes of multiple Folder objects which contains Folders and Files and so on. How to design the database to persist the data?
Thank you for your help. Please provide some related links if possible.
[ April 12, 2004: Message edited by: richard chang ]
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

There are three common designs that I am aware of. The easiest is a single table with a single parent reference. Multiple children can have the same parent, giving you a one to many relationship like a directory structure.
As a Class it would look like this:

The second common design has a table that defines the folder, and a separate joining table that defines the parent-child relationships:

This design can also be many-to-many if desired.
Two big problems with this design is where to start, and the cost of traversing the tree. THe 'where to start' problem is usually solved by having either a root node 'id=1 is the root and everything comes off it', or defining any folder with a null parent as a root node. The second problem is that to build a list of all of the folders, you have to start with the root folders, then load all of their children, then all of their children, etc etc until you load the whole tree. Since each query is a separate database query, it can be a significant problem if you constantly load large sections of the structure (ignore caching, assume the data is changing constantly).
This brings us to the third design, which I've encountered, but never used. It cheats by denormalising the first N steps of the directory structure and then loading anything beyond this in one of the previous ways. Lets say you're designing a news site, and in your design you define 4 layers of menus that gets you to 90% of your stories. You can define the extra data like this to allow you to load all of these folders in a single database statement:

The folderIds still load from the Folder table, and the bottom folder can still have children, but it can significantly reduce the impact of needing to reload the entire tree structure.
Hope this is what you were looking for.
I agree. Here's the link:
subject: how to map composite objects to database
It's not a secret anymore!