Reputation: 18133
My app has leagues, and each league can have any number of competitions. I use .hbm.xml files to set up an association between leagues and competitions. I've configured it as follows:
<set name="competitions" table="leagueCompetitions" lazy="false">
<meta attribute="property-type"><![CDATA[Set< Competition >]]></meta>
<meta attribute="default-value"><![CDATA[new HashSet< Competition >()]]></meta>
<key column="leagueId"/>
<many-to-many column="competitionId"
unique="true"
lazy="false"
class="com.example.model.Competition"/>
</set>
I have a DAO method that retrieves a list of leagues that essentially comes down to
Query query = session.createQuery( "from League" );
return query.list();
I wrote some code to count the competitions, and it was as simple as
if ( league.getCompetitions().size() > 0 ) { ... blahditty blah ... }
But it failed because getCompetitions() always is an empty set.
Question: When I use LeagueDAO.list() to get a list of leagues, should not each league have all of its competitions loaded as well?
Upvotes: 0
Views: 886
Reputation: 18133
Turns out that my hbm.xml configuration was invalid. I had a many-to-many configuration on one table, and a many-to-one on the opposite side of the association. The result was just a mess.
Upvotes: 1
Reputation: 20323
Add cascade="all"
<set name="competitions" table="leagueCompetitions" lazy="false" cascade="all">
<meta attribute="property-type"><![CDATA[Set< Competition >]]></meta>
<meta attribute="default-value"><![CDATA[new HashSet< Competition >()]]></meta>
<key column="leagueId"/>
<many-to-many column="competitionId"
unique="true"
lazy="false"
class="com.example.model.Competition"/>
Upvotes: 2