Monday, September 3, 2007

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

Unidirectonal many-to-many (join table)) association

Hibernate Doc (Chap 8.3.4)

person(many) -> address(many)

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

::Java Operation::


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

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

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

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

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

select addresses0_.personId as personId1_, addresses0_.addressId as addressId1_, address1_.addressId as addressId3_0_ from PersonAddress addresses0_ left outer join ADDRESS address1_ on addresses0_.addressId=address1_.addressId where addresses0_.personId=?

[Association Mapping List]


nada said...

Is this really a many-to-many relationship?

Isn't the constraint "unique = true" in:
@JoinColumn(name="personId", unique = true)
preventing the existence of multiple entries of the same personId in the Table PersonAddress?

Ryan said...

I agree, that unique constraint makes this effectively a one-to-many relationship.

Atif-Mehmood said...

Excellent, superb, fantastic

You cant explain more simple than this

איתי זיידמן said...

First of all thanks for the great post. I, of course, have a small question: If for some reason I would need to get all the people living in a specific address then the @JoinTable annotation on the Address entity would be exactly the same only the joinColumns and inverseJoinColumns properties would be opposite. Am I correct?

איתי זיידמן said...

In my previous comment I meant of course if I wanted to additionally have the ability to retrieve all people living in an address meaning each entity will contain a Set of the other entity