Let's extend our model of the world to include heads of state.
This is the data in the HEAD_OF_STATE table:
HOS_ID
CTRY_ID
HOS_NAME
1
122
President Mikheil Saakashvili
2
14
President Horst Köhler
3
73
President Karolos Papoulias
We map the HeadOfState class to the table and include a
@OneToOne
association with the Country class.
@Entity
@Table(name="HEAD_OF_STATE")
public class HeadOfState {
@Id
@GeneratedValue
@Column(name="HOS_ID")
private Integer id;
@Column(name="HOS_NAME")
private String name;
@OneToOne
@JoinColumn(name="CTRY_ID")
private Country country;
// Accessors
}
The CTRY_ID column, which is specified in the
@JoinColumn
annotation, names the foreign key column on the HEAD_OF_STATE table which is used to join the two tables together.
We make the association bidirectional by adding a reference to HeadOfState
on the Country class.
Remember to add mappedBy on the
@OneToOne
annotation to ensure that only one side manages the relationship.
We can now access the head of state for a country
Country georgia = (Country) session.load(Country.class, 122);
System.out.println("The head of state for " + georgia.getName() +
" is " + georgia.getHeadOfState().getName());
or the country represented by a head of state.
HeadOfState hos = (HeadOfState) session.load(HeadOfState.class, 1);
System.out.println(hos.getName() + " is head of state for " +
hos.getCountry().getName());