Monday, September 3, 2007

Hibernate: Annotation one-to-one (join table)

Unidirectonal one-to-one (join table) association

Hibernate Doc (Chap 8.3.3)

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

::DB Schema::
person(personId)
address(addressId)
personaddress(personId, addressId)

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

::Annotation::

@Entity
@Table(name = "PERSON")
@Entity
@Table(name = "PERSON")
public class Person {

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

  @OneToOne(optional=true)
  @JoinTable(name="PersonAddress",
    joinColumns = {
      @JoinColumn(name="personId", unique = true)           
    },
    inverseJoinColumns = {
      @JoinColumn(name="addressId")
    }     
  )
  private Address address;
}


@Entity
@Table(name = "ADDRESS")
public class Address {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "addressId")
  private int id;  
}



::Generated SQL::
- person.getAddress();

select person0_.personId as personId2_1_, person0_1_.addressId as addressId3_1_, address1_.addressId as addressId4_0_ from PERSON person0_ left outer join PersonAddress person0_1_ on person0_.personId=person0_1_.personId left outer join ADDRESS address1_ on person0_1_.addressId=address1_.addressId where person0_.personId=?

[Association Mapping List]

6 comments:

Prats said...

thanks for the psot

Unknown said...

simple but very handy reference. arigato gozaimasu

Anonymous said...

this one-to-one via join table does not work for me with toplink. Is there any difference using hiberate or toplink for jpa? thx

Anonymous said...

Hello
http://www.manga-reader.com/ - klonopin mg

Klonopin may also increase or precipitate the incidence of the onset of generalized of tonoic-clonic seizures or grand mal requiring the addition of appropriate anticonvulsants or an increase in the dosage.
[url=http://www.manga-reader.com/]clonazepam online[/url]

Klonopin may also increase or precipitate the incidence of the onset of generalized of tonoic-clonic seizures or grand mal requiring the addition of appropriate anticonvulsants or an increase in the dosage.
buy klonopin

Clonazepam is available as an oral disintegrating tablet which makes it easy to use.

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..

Anonymous said...

Thanks it works great.