Monday, September 3, 2007

Hibernate: Annotation one-to-one (foreign-key)

Bidirectonal one-to-one (foreign-key) association

Hibernate Doc (Chap 8.4.2)


::Relationship::
person(one) <-> address(one)

::DB Schema::
person(id, addressId)
address(id)

::Java Operation::
person.getAddress();
address.getPerson();

::Annotation::

@Entity
@Table(name="PERSON")
public class Person {
   
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name="personId")
  private int id;
 
  @ManyToOne
  @JoinColumn(name="addressId")     // inverse = false
  private Address address;
}


@Entity
@Table(name = "ADDRESS")
public class Address {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "addressId")
  private int id;

  @OneToOne(mappedBy="address")  // inverse=true, pointnig Person's address field
  private Person person;   
}



::Generated SQL::
- person.getAddress();
select person0_.personId as personId2_1_, person0_.addressId as addressId2_1_, address1_.addressId as addressId3_0_ from PERSON person0_ left outer join ADDRESS address1_ on person0_.addressId=address1_.addressId where person0_.personId=?

- address.getPerson();
select person0_.personId as personId2_1_, person0_.addressId as addressId2_1_, address1_.addressId as addressId3_0_ from PERSON person0_ left outer join ADDRESS address1_ on person0_.addressId=address1_.addressId where person0_.addressId=?

[Association Mapping List]

No comments: