Monday, September 3, 2007

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

Bidirectonal many-to-many (join table) association

Hibernate Doc (Chap 8.5.3)


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

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

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

::Annotation::

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

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

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

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

3 comments:

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?