I'm receiving a NonUniqueObjectException and I'm not sure how I can avoid it. I know what the exception means, and I pretty much know why I'm getting it, but I'm hoping I'm just missing an easy way to fix it. Here's my scenario:
I have a simple Message class:
Code:
@Entity
public class Message {
private int id;
private String value;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProjectEntityMessage other = (ProjectEntityMessage) obj;
if (id != other.id)
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
Which is being used inside of a Spring Hibernate DAO kind of like this:
Code:
Message m1 = new Message(1, "abc");
Message m2 = new Message(2, "def");
Message m3 = new Message(1, "abc");
// parent has a List<Messages> attribute
Parent p1 = new Parent();
parent.getMessages().add(m1);
parent.getMessages().add(m2);
Parent p2 = new Parent();
parent.getMessages().add(m2);
parent.getMessages().add(m3);
// has a List<Parent> attribute
ParentOfParent eldest = new ParentOfParent();
eldest.getParents().add(p1);
eldest.getParents().add(p2);
getHibernateTemplate().save(eldest);
The logs show all of the insert statements for inserting p1 go off ok, but as soon as p2 tries to handle the m3 message, I get the NonUniqueObjectException. This example is a simplification, but my use case requires that I may have to create multiple objects corresponding to a single database row. I know that m1 != m3, but m1.equals(m3) should be true and I thought Hibernate used that to determine identity.
What am I missing?