Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • 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

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

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) { = phone;


And this is

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 .

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.
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!