lish level up
«previous  next»


Getting Started
Associations
HQL



One-To-One Association


Let's extend our model of the world to include heads of state.
HEAD_OF_STATE and COUNTRY tables
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.
@OneToOne (mappedBy="country")
@JoinColumn(name = "CTRY_ID")
private HeadOfState headOfState;
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());
»
See Also
 
Quick Start
Get up and running in minutes with all the SQL and Java code from this section

Feedback
If you have any comments or suggestions about level up, please visit lishblog or email mark.lishman@googlemail.com