Hibernate second-level cache for many-many relationship in a joining table


#1

Hello,

I am not able to get the Hibernate L2 caching work for relationships stored in a joining/bridging table for a many to many relationship between two entities.

Description: I have two entities viz. Attribute.java and Organization.java which are mapped to tables ATTRIBUTE and ORGANIZATION respectively. They have a many-many relationship i.e. an attribute could be part of many organizations and an organization could have many attributes. In order to maintain this relationship, there is a third table ATTRIBUTE_ORGANIZATION which maintains this relationship.

I am able to L2 cache the Attribute and Organization entities by modifying the respective hbm files however not able to cache the relation between Attribute and Organization.
The relationship is loaded lazily through following mapping in hbm files e.g. following entries in hbm files:

Attribute.hbm.xml:

    <set name="organizations" inverse="false" lazy="true" table="attribute_organization" fetch="select">
        <key>
            <column name="attribute_id" not-null="true" />
        </key>
        <many-to-many foreign-key="fk_Attr_Org" entity-name="com.test.hibernate.Organization">
            <column name="organization_id" not-null="true" />
        </many-to-many>
    </set>

Organization.hbm.xml:

    <set name="attributes" cascade="all" inverse="true" lazy="true" table="attribute_organization" fetch="select">
        <key>
            <column name="organization_id" not-null="true" />
        </key>
        <many-to-many foreign-key="fk_Org_Attr" entity-name="com.test.hibernate.Attribute">
            <column name="attribute_id" not-null="true" />
        </many-to-many>
    </set>

Can you advise what are the ways to cache these many to many relations through hibernate l2 caching?


#2

You forgot to add the:

<cache usage="read-write/>

Inside the <set> elements.

For more details, check out this antique Hibernate doc. Since 2006, we prefer annotations which are better supported anyway.