Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

onetomany relation ship

 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I am new to Hibernate.I tried onetomany relation ship between Person and Address classes.
My person.hbm.xml file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="onetomanynew">
<class name="Person">
<id name="personId">
<generator class="native"/>
</id>
<property name="personName"/>
<set name="address" cascade="all" >
<key column="ParentpersonId"/>
<one-to-many class="Address" />
</set>
</class>
</hibernate-mapping>

address.hbm.xml is a simple one for persisting the data.

And my client class is

public static void main(String[] args) throws Exception
{
Address a1=new Address();
a1.setAddress("VSP");
Address a2=new Address();
a2.setAddress("VSP1...");
Person p=new Person();
p.setPersonName("Anil ");
Set s=new HashSet();
s.add(a1);
s.add(a2);
p.setAddress(s);
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction t=session.beginTransaction();
session.save(a1);---------1
session.save(a2);---------2
session.save(p);

t.commit();
session.close();

}

If i comment the lines 1 and 2 i am getting error

Exception in thread "main" net.sf.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: 0, of class: onetomanynew.Address.

If i don't comment those lines it is persisting well.

I want to do lik this.

If i persist Person Class then Adress class should also persist.

How to do that ?

And why am i getting that error ?

Please explain that.


Regards

Anil Kumar
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic