Search code examples
hibernatehyperlinkmappingmany-to-many

Is this approach for many-to-many mapping possible in Hibernate?


I've got three tables: item, node and item_node as linking table, which of course contains IDs of item and node.

Can I map the linking table (item_node) in such a way that corresponding class ItemNode holds somehow references to Item and Node classes? Is there any known practice for mapping link tables in m:n relationships?

I would imagine something like this:

<class name="test.model.ItemNode" table="ITEM_NODE">
    <composite-id name="ID" class="test.model.INCompID">
        <key-property name="item" column="ITEM_ID" />
        <key-property name="node" column="NODE_ID"/>
    </composite-id>
</class>

where INCompID is class for composite ID:

public class INCompID {

private Item item;
private Node node;

//getters, setters and overriden 
//equals() and hashCode() methodes
}

Item and Node are already mapped and working properly by themselves.

I know that this is not usual approach for dealing with many-to many relationships, but I'm having quite annoying problem with standard set/bag-based approach, because of the lousy lazy initialization exception, and there is no way to load these collections eagerly, because they would contain enormous amount of data (hundreds of thousands of rows in DB tables).
Spring AOP is used for transaction management. OpenSessionInViewFilter/Interceptor doesn't seem to be helpful for this particular problem either, so...


Solution

  • Can I map the linking table (item_node) in such a way that corresponding class ItemNode holds somehow references to Item and Node classes?

    You sure can. Another way to view this is imagining that ItemNode may hold a property by itself (for instance, "sequence_no"). Thus, ItemNode can effectively be an Entity by itself, instead of just a link between Item and Node.

    See this example from the Hibernate test suite:

    https://github.com/hibernate/hibernate-core/tree/master/hibernate-core/src/test/java/org/hibernate/test/manytomanyassociationclass

    Is there any known practice for mapping link tables in m:n relationships?

    There are personal preferences, but not best practices. There are people that realize that things can change, and they get prepared for it: they map the relationship as an entity. Then, there are people who believe that this relationship should be viewed just as a relationship in the OO model too.