JPA 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

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. A particular user could be related to several accounts. If you define the Meta-Data for these classes as follows

<entity-mappings>
    <entity class="User">
        <table name="USER"/>
        <attributes>
            <id name="id">
                <column name="USER_ID"/>
            </id>
            ...
        </attributes>
    </entity>

    <entity class="Account">
        <table name="ACCOUNT"/>
        <attributes>
            <id name="id">
                <column name="ACCOUNT_ID"/>
            </id>
            ...
            <many-to-one name="user">
                <join-column name="USER_ID"/>
            </many-to-one>
        </attributes>
    </entity>
</entity-mappings>

This will create 2 tables in the database, one for User (with name USER ), and one for Account (with name ACCOUNT and a column USER_ID ), as shown below.



Things to note :-

  • If you wish to specify the names of the database tables and columns for these classes, you can use the element table (under the entity element) and the attribute name (on the column element)
  • If you call PM.deletePersistent() on the end of a 1-1 unidirectional relation without the relation and that object is related to another object, an exception will typically be thrown (assuming the RDBMS supports foreign keys). To delete this record you should remove the other objects association first.


Bidirectional

This relationship is described in the guide for 1-N relationships. In particular there are 2 ways to define the relationship. The first uses a Join Table to hold the relationship. The second uses a Foreign Key in the "N" object to hold the relationship. Please refer to the 1-N relationships bidirectional relations since they show this exact relationship.