0

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?

Marvo
  • 17,845
  • 8
  • 50
  • 74

2 Answers2

2

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"/>

mprabhat
  • 20,107
  • 7
  • 46
  • 63
  • Thanks, but doesn't seem to make any difference in Hibernate's behavior. And [I read earlier](https://community.jboss.org/wiki/AShortPrimerOnFetchingStrategies) than "select" is the default. – Marvo Apr 30 '12 at 03:31
  • Also are you able to save it without cacade="all", I think you should be getting exception like "object references an unsaved transient instance - save the transient instance before flushing" – mprabhat Apr 30 '12 at 03:40
  • If you are able to save then with this configuration you should be able to load also, what all tables you have ? – mprabhat Apr 30 '12 at 06:02
  • I have league, competition, and leagueCompetitions. Thanks for confirming that this should work. – Marvo Apr 30 '12 at 06:30
1

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.

Marvo
  • 17,845
  • 8
  • 50
  • 74