Monday, September 3, 2007

Hibernate: Annotation one-to-many/many-to-one

Bidirectonal one-to-many/many-to-one association

Hibernate Doc (Chap 8.4.1)

person(many) <-> address(one)
- person A and person B live in address AA

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

::Java Operation::


public class Person {
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;
  @JoinColumn(name="addressId")     // inverse = false
  private Address address;

@Table(name = "ADDRESS")
public class Address {

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

  @OneToMany(mappedBy="address")  // pointing Person's address field
  @Column(name="personId")    // inverse=true
  private Set<Person> people;

::Generated SQL::

[Association Mapping List]


dminer said...

@Column(name="personId") in Address table is little confusing to me. Does it mean that there will be a personId column in Address table ? What does it mean to have inverse=true ?

Since its Person(many) to Address(one), Person is the only table that will have addressId to keep the relation. If so, what does Column(name='personId') achieve in Address Table ?

-- Dminer

Narayana Enaganti said...

can u send a end to end example for me.. my id

alternateStory said...


Thanks for your post! It's really helpful!

How ever, I am getting an error when I try to export schema -

Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: ADDRESS, for columns: [org.hibernate.mapping.Column(personId)]

Any idea why?

stijn1989 said...

The @Column is wrong in the Address class. It must be a @JoinColumn.

Anonymous said...

Nice post

Gopi said...


In the above code, please help me out in making the foreign_key(addressid) as null while i delete the address entry from address table?


Gopi said...


If i delete the "Address" entity, i want to make the joinedcolumn in PERSON entity as "null"

How to achieve it, could you help this?


Unknown said...

Plz some one tell me How i use one to many mapping in hibernate for creation of three tables.

Thanks in advance

Plz rply its argent

Sayan Guharoy said...

A typical metadata ORM model is create by xml mapping style,alternatively we can use hibernate annotation to design our persistance class.
See the below to example one with annotaion and one without it

Bajrang Kar said...

Not working for me.
In place of this, I tried to combine to Uni's & worked.
private Set&rt;Address&rt; address;
private Student student;

Why it is not working with mappedBy?? Help!