• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with One-to-many

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

I am new to Hibernate and i am trying to learn.I am trying for one-to-many mapping and i am getting this net.sf.hibernate.NonUniqueObjectException exception.


This is my User.java


public class User {
private int userId;
private String userName;
private Set phone;;
/** Creates a new instance of User */
public User() {
}

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public Set getPhone() {
return phone;
}

public void setPhone(Set phone) {
this.phone = phone;
}

}

And this is Phone.java


public class Phone {
private int phoneId;
private long number;

/** Creates a new instance of Phone */
public Phone() {
}

public int getPhoneId() {
return phoneId;
}

public void setPhoneId(int phoneId) {
this.phoneId = phoneId;
}

public long getNumber() {
return number;
}

public void setNumber(long number) {
this.number = number;
}



}

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="newonetomany">
<class name="User">
<id name="userId">
<generator class="native"/>

</id>

<set name="phone" cascade="all" >
<key column="fklUserId"/>
<one-to-many class="Phone"/>


</set>
<property name="userName"/>
</class>

</hibernate-mapping>


Main.java

try
{
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction t=session.beginTransaction();
User u1=new User();
u1.setUserName("kumar");

Phone p=new Phone();
p.setNumber(1);


Phone p1=new Phone();
p1.setNumber(2);


Set s=new HashSet();
s.add(p);
s.add(p1);
//session.save(p);
//session.save(p1);

u1.setPhone(s);

session.save(u1);

session.flush();
t.commit();
session.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}



If i persist Phone object seperately ,it is working fine.But if i do with out persisting the phone object.It is throwing the above exception.Please see the commented line of code i.e session.save(p) .


Why i am getting that exception ??

Thanks

Anil Kumar
 
Hongli Li
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if phone is not shared by multiple users then phone should be mapped as a value type, and I think you need to implement hashCode() and equals() method for Phone, since hibernate don't know how to distinguish those two phones in your code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic