If u have a many-to-many relation then there is no singular PARENT but multiple parents (well I would thus not even use the term "parent") and the Child class should either have a reference to a Collection of Parents or no parent at all.
Code:
public class Container {
private int id;
private Collection<Content> contents = new ArrayList<Content>();
public Collection<Content> getContents() {
return contents;
}
private void setContents(Collection<Content> contents) {
this.contents = contents;
}
}
public class Content {
private int id;
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
<hibernate-mapping>
<class name="Container">
<id name="id" access="field">
<generator class="native" />
</id>
<bag name="contents" cascade="save-update">
<key></key>
<many-to-many class="Content"></many-to-many>
</bag>
</class>
<class name="Content">
<id name="id" access="field">
<generator class="native" />
</id>
<natural-id>
<property name="name" not-null="true"/>
</natural-id>
</class>
</hibernate-mapping>
I believe u did something like the following:
Code:
final Session sess = sf.openSession();
Container container = new Container();
Content content = new Content();
content.setName("A");
container.getContents().add(content);
Transaction tx = sess.beginTransaction();
sess.save(container);
tx.commit();
tx = sess.beginTransaction();
container = new Container();
content = new Content();
content.setName("A");
container.getContents().add(content);
sess.save(container);
tx.commit();
And of course the above will generate:
Violation of unique constraint
What I would suggest u to do is (depending on the semantics of your domain objects) if u are indeed going to have the same content in more than one containers, don't create a new content blindly but first try to load an existing one:
Code:
final Session sess = sf.openSession();
Container container = new Container();
Content content = new Content();
content.setName("A");
container.getContents().add(content);
Transaction tx = sess.beginTransaction();
sess.save(container);
tx.commit();
tx = sess.beginTransaction();
container = new Container();
content = (Content) sess.createQuery("from Content where name like :name").setString("name", "A").uniqueResult();
container.getContents().add(content);
sess.save(container);
tx.commit();
sess.close();
But I also doubt if what u wanted was indeed a parent-child relation whence the relation would be one-to-many and not many-to-many.