Finally, we map a many-to-many association between heads of state and their visits to one or more countries.

The VISIT table contains this data:
| CTRY_ID |
HOS_ID |
| 14 |
3 |
| 48 |
3 |
| 149 |
3 |
| 73 |
2 |
| 73 |
1 |
A @ManyToMany
association relies on a join table which consists of combinations of
primary key values from the two tables which make up the relationship.
In this case our association table is called VISIT.
We add this code to the HeadOfState class:
@ManyToMany
@JoinTable (
name="VISIT",
joinColumns = {@JoinColumn(name="HOS_ID")},
inverseJoinColumns={@JoinColumn(name="CTRY_ID")}
)
private Set<Country> visited = new HashSet<Country>();
...
public void addVisit(Country country) {
this.visited.add(country);
country.getVisitors().add(this);
}
To make the association bidirectional, we add this code to the Country class:
@ManyToMany(mappedBy="visited")
private Set<HeadOfState> visitors = new HashSet<HeadOfState>();
HeadOfState now references Country in two different ways;
a one-to-one association to determine which country the head of state represents and
a many-to-many association to determine which countries a head of state has visited.
The addVisit() convenience method is used to record a visit.
session.beginTransaction();
HeadOfState saakashvili = (HeadOfState) session.load(HeadOfState.class, 1);
Country gambia = (Country) session.load(Country.class, 147);
saakashvili.addVisit(gambia);
session.getTransaction().commit();
We can determine which countries a particular head of state has visited.
HeadOfState saakashvili = (HeadOfState) session.load(HeadOfState.class, 1);
System.out.println(saakashvili.getName() +
" is head of state for " + saakashvili.getCountry().getName() +
" and has visited");
for (Country country : saakashvili.getVisited()) {
System.out.println(" " + country.getName());
}
And, because the association is bidirectional, we can also show which heads of state have visited a particular country.
Country georgia = (Country) session.load(Country.class, 73);
System.out.println(georgia.getName() + " has been visited by ");
for (HeadOfState hos : georgia.getVisitors()) {
System.out.println(" " + hos.getName());
}
|