Monday, September 3, 2007

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

Unidirectonal one-to-many (join table) association

Hibernate Doc (Chap 8.3.1)

person(one) -> address(many)

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


Anonymous said...

I saw one problem with this kind of mapping.
Lets say there is a person named "Tom" and he has two addresses.
If I execute following code it returns a list which contains two Person object. Both object refers to same and only database row. Both objects contains a list of 2 addresses. My question here is why does list contains 2 Person object and not one (as there is only one row in database with name Tom).

Here is the code.

DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SEOContent.class).add(Restrictions.eq("name","Tom"));
List list = this.getHibernateTemplate().findByCriteria(detachedCriteria);

If I change the mapping inside Address to following, same java code returns a list with one Person object in it.

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "personid")
private Person person;

Prasad said...

Small correction in the last post. In both cases it does not work, if I use FetchType.EAGER. So strangely EAGER type triggers the outer join sql, which returns more than one row in result. Hibernate simply builds the same no. of object as in the result set.

Anonymous said...

Welche anmutige Phrase viagra generika online kaufen viagra kaufen [url=http//]viagra rezeptfrei[/url]

Anonymous said...

Hay otras faltas [url= ]viagra generico sildenafil [/url] Mismo discutŠ“­an ya recientemente viagra es bueno

Alprazolam said...

Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!

Purchase Adderall said...

Very efficiently written article. It will be helpful to anybody who utilizes it, as well as myself. Keep doing what you are doing - for sure i will check out more posts.