Monday, September 3, 2007

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

Bidirectonal one-to-many/many-to-one (join table) association

Hibernate Doc (Chap 8.5.1)


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


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

::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;

  @OneToMany
  @JoinTable(name = "PersonAddress",
    joinColumns = {
      @JoinColumn(name="personId", unique = true)           
    },
    inverseJoinColumns = {
      @JoinColumn(name="addressId")
    }
  )
  private Set<Address> addresses;
}


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

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

  @ManyToOne(optional=true)
  @JoinTable(name = "PersonAddress",
    joinColumns = {
      @JoinColumn(name="addressId")
    },
    inverseJoinColumns = {
      @JoinColumn(name="personId")
    }
  )
  private Person person;   
}



::Generated SQL::
- person.getAddresses();
select addresses0_.personId as personId2_, addresses0_.addressId as addressId2_, address1_.addressId as addressId3_0_, address1_1_.personId as personId4_0_, person2_.personId as personId2_1_ from PersonAddress addresses0_ left outer join ADDRESS address1_ on addresses0_.addressId=address1_.addressId left outer join PersonAddress address1_1_ on address1_.addressId=address1_1_.addressId left outer join PERSON person2_ on address1_1_.personId=person2_.personId where addresses0_.personId=?

- address.getPerson();
select address0_.addressId as addressId3_1_, address0_1_.personId as personId4_1_, person1_.personId as personId2_0_ from ADDRESS address0_ left outer join PersonAddress address0_1_ on address0_.addressId=address0_1_.addressId left outer join PERSON person1_ on address0_1_.personId=person1_.personId where address0_.addressId=?

[Association Mapping List]

3 comments:

Doug said...

This is one of the best reference site about jpa and hibernate!! Keep up the good work!

Eric said...

Just a note to say that, to my knowledge, @FilterJoinTable doesn't work on a many-to-one association.
I had to use a many-to-many instead on the Address side to apply my FilterJoinTable.

Anonymous said...

thanks for the post helped a lot in the right time ;) hurray