• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with One-to-many  RSS feed

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

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;



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


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

<property name="userName"/>



Session session=HibernateUtil.getSessionFactory().openSession();
Transaction t=session.beginTransaction();
User u1=new User();

Phone p=new Phone();

Phone p1=new Phone();

Set s=new HashSet();



catch(Exception e)

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 ??


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.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!