Hello.
i have two classes with many-to-many relationship, with bidirectional link.
the problem is, that in one class i cannot remove elements from a set that makes one part of that link, using remove()
Code:
stuff[i].getCategories().remove(currentCategory); //works
currentCategory.getStuff().remove(stuff[i]); //does not remove element from collection; returns false
both objects are in transient state, but if i attach them before doing this, it makes no difference.
however, if i try to remove object from collection using iterator, it works
Code:
stuff[j].getCategories().remove(currentCategory);
long id = stuff[i].getId();
for(Iterator<Stuff> it = currentCategory.getStuff().iterator(); it.hasNext();)
{
Stuff s = it.next();
if(s.getId() == stuff[i].getId())
{
it.remove();
break;
}
}
here is an excerpt from declaration of both classes
Code:
...
public class Stuff implements Comparable, Serializable{
...
private java.util.SortedSet<Category> categories;
/**
* @hibernate.set
* role="categories"
* table="CATEGORY_TO_STUFF"
* sort="natural"
* batch-size="50"
* cascade="all"
* inverse="true"
* lazy="true"
* @hibernate.collection-key
* column="CATEGORY_FK"
* @hibernate.collection-many-to-many
* class="imarine2.Category"
* column="STUFF_FK"
*/
public java.util.SortedSet<Category> getCategories()
{
return this.categories;
}
protected void setCategories(java.util.SortedSet<Category> categories)
{
this.categories = categories;
}
...
public Stuff()
{
categories = new TreeSet<Category>();
...
}
public int compareTo(Object object) {
Stuff stuff = (Stuff)object;
if(stuff.id < id)
return -1;
if(stuff.id > id)
return 1;
return 0;
}
public boolean equals(Object o)
{
if(!(o instanceof Stuff))
return false;
if(((Stuff)o).getId() == getId())
return true;
return false;
}
}
Code:
...
public class Category implements Comparable, Serializable{
...
private java.util.SortedSet<Stuff> stuff;
/**
* @hibernate.set
* role="stuff"
* table="CATEGORY_TO_STUFF"
* sort="natural"
* batch-size="50"
* cascade="all"
* inverse="false"
* lazy="true"
* @hibernate.collection-key
* column="STUFF_FK"
* @hibernate.collection-many-to-many
* class="imarine2.Stuff"
* column="CATEGORY_FK"
*
*/
public java.util.SortedSet<Stuff> getStuff() {
return this.stuff;
}
protected void setStuff(java.util.SortedSet<Stuff> stuff) {
this.stuff = stuff;
}
...
public Category()
{
stuff = new TreeSet<Stuff>();
...
}
public boolean equals(Object o)
{
if(!(o instanceof Category))
return false;
if(((Category)o).getId() == this.getId())
return true;
return false;
}
public int compareTo(Object object) {
Category category = (Category)object;
if(category.id < id)
return -1;
if(category.id > id)
return 1;
return 0;
}
}