JDO : N-1 Relationships

You have a N-to-1 relationship when an object of a class has an associated object of another class (only one associated object) and several of this type of object can be linked to the same associated object. From the other end of the relationship it is effectively a 1-N, but from the point of view of the object in question, it is N-1. You can create the relationship in 2 ways depending on whether the 2 classes know about each other (bidirectional), or whether only the "N" side knows about the other class (unidirectional). These are described below.


Unidirectional (Join Table)

For this case you could have 2 classes, User and Account, as below.

so the Account class ("N" side) knows about the User class ("1" side), but not vice-versa and the relation is stored using a join table. A particular user could be related to several accounts. If you define the XML metadata for these classes as follows

<package name="mydomain">
    <class name="User" identity-type="datastore">
        ...
    </class>

    <class name="Account" identity-type="datastore">
        ...
        <field name="user" persistence-modifier="persistent">
            <join/>
        </field>
    </class>
</package>

alternatively using annotations

public class Account
{
    ...

    @Join(table="ACCOUNT_USER")
    User user;
}

For RDBMS this will create 3 tables in the database, one for User (with name USER), one for Account (with name ACCOUNT), and a join table (with name ACCOUNT_USER) as shown below.

Note that in the case of non-RDBMS datastores there is no join-table, simply a "column" in the ACCOUNT "table", storing the "id" of the related object

Things to note :-

  • If you wish to specify the names of the database tables and columns for these classes, you can use the attribute table (on the class element), the attribute name (on the column element) and the attribute name (on the column attribute under join

Unidirectional (ForeignKey)

Here you have the same two classes as above but you have a foreign-key in the table of Account. For this case, just look at the 1-1 Unidirectional documentation since it is identical.


Bidirectional

This relationship is described in the guide for 1-N relationships. In particular there are 2 ways to define the relationship with RDBMS : the first uses a Join Table to hold the relationship, whilst the second uses a Foreign Key in the "N" object to hold the relationship. For non-RDBMS datastores each side will have a "column" (or equivalent) in the "table" of the N side storing the "id" of the related (owning) object. Please refer to the 1-N relationships bidirectional relations since they show this exact relationship.