persistence@glassfish.java.net

how to map Self-referencing table ManyToMany relationship

From: reljicb <bojan.reljic_at_gmail.com>
Date: Thu, 12 Aug 2010 08:26:04 -0700 (PDT)

Hi!

I'm not very experienced with persistence, so if anybody of persistence
experts have idea how to solve this, please assist.

I have database that models bi-directional graphs.
There is a Node table:

   Table node
   ==========
   id INT
   name VARCHAR
   nodeType INT

Any Node can be linked to many other nodes. I use Link table as association
table to link them.

   Table link
   ==========
   nodeId1 INT
   nodeId2 INT

When I generate persistence entities (NetBeans), I get a class member
"linkedNodes" defined as following:

   @JoinTable(name = "link",
                   joinColumns = {_at_JoinColumn(name = "nodeId1",
referencedColumnName = "id", nullable = false)},
                   verseJoinColumns = {_at_JoinColumn(name = "nodeId2",
referencedColumnName = "id", nullable = false)})
   @ManyToMany
   private Collection<Node> linkedNodes;

The problem is that this JPA mapping behaves as if the graph is
unidirectional - linkedNodes collection contains ONLY those nodes which are
linked to this one in nodeId1->nodeId2 direction manner. In other words,
table Link is queried for only those records where Id of the current node is
in nodeId1 filed, and Ids of other (linked) nodes are in nodeId2 column, and
not vice-verse.

This perfectly makes seanse when ManyToMany relationship is defined between
two different tables.

But here I want to obtain all the nodes which are linked to the current one.
In other words, when Id of current node is in EITHER nodeId1 OR nodeId2
column of the Link table.

Thanks in advance.
Your help is very much appreciated.

Bojan

-- 
View this message in context: http://old.nabble.com/how-to-map-Self-referencing-table-ManyToMany-relationship-tp29419942p29419942.html
Sent from the java.net - glassfish persistence mailing list archive at Nabble.com.