Monday, September 3, 2007

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

Hibernate Doc (Chap 8.3.2)



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

ex) person A and person B live in address AA

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

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


::Annotation::

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

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

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


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



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

select person0_.personId as personId2_1_,
person0_1_.addressId as addressId3_1_,
address1_.addressId as addressId4_0_
from PERSON person0_ left outer join PersonAddress person0_1_ on person0_.personId=person0_1_.personId
left outer join ADDRESS address1_ on person0_1_.addressId=address1_.addressId
where person0_.personId=?

[Association Mapping List]

2 comments:

Anonymous said...

When I attempt this, I get a null pointer exception on schema generation...

alberto said...

And if I want to implement address.getPerson() ? How I can do it?