Monday, September 3, 2007

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

Bidirectonal many-to-many (join table) association

Hibernate Doc (Chap 8.5.3)

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;

  // mapping owner
  @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;

  @ManyToMany(mappedBy="addresses")  // map info is in person class
  private Set<Person> people;

::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=?

- address.getPeople();
select people0_.addressId as addressId1_, people0_.personId as personId1_, person1_.personId as personId2_0_ from PersonAddress people0_ left outer join PERSON person1_ on people0_.personId=person1_.personId where people0_.addressId=?

[Association Mapping List]


James Adams said...

Thanks for making this available, it's quite helpful!

Guilherme said...
This comment has been removed by the author.
Guilherme said...

Thank you very much, but my personaddress table is not being filled in the database. (The others are).

Do you have any idea what might be wrong?