Hmm, I said I had many-to-many working, largely. In fact, I don't, and I can't see why. Here's the relevant chunk from Team.hbm.xml:
<set
name="competitions"
table="team_competition"
lazy="false"
inverse="false"
cascade="save-update"
sort="unsorted">
<key
column="team_id"></key>
<many-to-many
class="myproject.om.Competition"
column="competition_id"
outer-join="auto" />
</set>
Here's the matching chunk from Competition.hbm.xml:
<set
name="teams"
table="team_competition"
lazy="false"
inverse="false"
cascade="save-update"
sort="unsorted">
<key
column="competition_id"></key>
<many-to-many
class="myproject.om.Team"
column="team_id"
outer-join="auto" />
</set>
I could swear this is just as in the examples I've seen. And yet it doesn't work when I run the following code, which retrieves an existing newly created Competition object from the database and then attempts to create and save 4 Team objects with this Competition assigned to them.
Code:
Competition premiership=dataService.findCompetition("English Premiership");
String[] teams=new String[] {"Chelsea","Arsenal","Liverpool","Everton"};
for (int i=0;i < teams.length;i++) {
Team team=dataService.findTeam(teams[i]);
if(team==null){
team=new Team(teams[i]);
HashSet compSet=new HashSet();
compSet.add(premiership);
team.setCompetitions(compSet);
team=dataService.storeTeam(team);
}
}
When I look at the database after this process has run, the bridging table ('team_competition') only has one record in it, which is for the last of the teams created in the code above. I experimented with setting 'inverse=true' on one of the tables, but this ended up with no bridging records at all being created. I must be doing something fundamentally wrong, but I really can't see what it is. Help!