Monday, September 3, 2007

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

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

Hibernate Doc (Chap 8.3.4)


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

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

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

::Annotation::

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

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

  @ManyToMany
  @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;
}



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

5 comments:

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?

Anonymous 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

Unknown 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?

Unknown 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