Monday, September 3, 2007

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

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

Hibernate Doc (Chap 8.4.2)


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


::DB Schema::
person(personId)
address(personId)


::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;
 
  @OneToOne
  @PrimaryKeyJoinColumn
  private Address address;
}


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

  @Id
  @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]

4 comments:

Arron Ferguson said...

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

Anonymous said...

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

Thanks

Nirav Assar said...

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

http://tadtech.blogspot.com/2007/03/hibernate-annotation-one-to-one-primary.html

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
id

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