Monday, September 3, 2007

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

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

Hibernate Doc (Chap 8.4.2)

person(one) <-> address(one)

::DB Schema::

::Java Operation::


public class Person {
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;
  private Address address;

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

  @Column(name = "personId")
  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_2_, address1_.personId as personId3_0_, person2_.personId as personId2_1_ from PERSON person0_ left outer join ADDRESS address1_ on person0_.personId=address1_.personId left outer join PERSON person2_ on address1_.personId=person2_.personId where person0_.personId=?

- address.getPerson();
select address0_.personId as personId3_2_, person1_.personId as personId2_0_, address2_.personId as personId3_1_ from ADDRESS address0_ left outer join PERSON person1_ on address0_.personId=person1_.personId left outer join ADDRESS address2_ on person1_.personId=address2_.personId where address0_.personId=?

[Association Mapping List]


Arron said...

Once again these examples you've posted are invaluable. Thank you!

Anonymous said...

some one get this example work ?? Please let me know :)


Nirav Assar said...

This example will not work. See my post on Tadaya's previous similar blog.

Asad said...

That is good post..well i am having a problem and it is driving me nuts.
i have a scenario in which each product it link to some other product.
table = product
id (primary key),
link(pointing to id)
this link can and cannot be null.its kind of parent child realtion in one table..after searching and found nothing i thought may b my design is bad so i split the product table
table = product

table = pr_link
both are foreign keys from product table. it is one to one relation and iam unable to fix it..please help thank you..