One mapping that doesn’t work well in Hibernate or Java
Jun 29, 2004 16:41 · 267 words · 2 minute read
Hibernate does a good job of managing relationships for you. If your data forms a nice object graph, not only do you not have to write SQL, you don’t even need to write Hibernate’s query language! Just traverse your graph and Hibernate will load objects as needed.
I’ve stumbled across a relationship that Hibernate doesn’t handle particularly well. Hibernate does a good job of staying true to the semantics of the Java collections framework. The exception to this is their “bag”, which is an unordered collection of items that can contain the same item multiple times. They use a List to represent this, but make it clear in the docs that the order is not maintained.
What I need is a little different from anything in java.util… It needs to be ordered like a List and provide for random access and update of elements like a List. But, any given item should only appear in there once. I tried mapping this with a List (ignoring the only appearing once in the list requirement for the moment) and it almost worked. Updating the list proved to be problematic though (details in this Hibernate Forum thread). My situation is complicated a little bit by the fact that this is a bidirectional many-to-many relationship that has this interesting collection on one side and a Set on the other.
Remarkably, I’m not the only one with this problem. I think that certain piece of data lend themselves to this structure. It would be nice to get a generic solution together for this (after meeting my specific application need, of course 🙂