I have a class which has a collection. Elements in the collection also have a collection. i am fetching the class instance and detaching it. Now i am updating the collection field to a new collection and then persisting the detached object. To my surpruise the objects collection now has the old elements and the new elements. How do i fix this as i had replaced the collection with a new one?
Here is the directory bean. It has a collection of numberBeans
@PersistenceCapable(detachable="true")
@FetchGroup(name="fet_num", members={@Persistent(name="numbers")})
public class DirectoryBean {
public DirectoryBean(String nameOfCity, ArrayList<NumberBean> numbers) {
super();
this.nameOfCity = nameOfCity;
this.numbers = numbers;
}
@Persistent
@PrimaryKey
private String nameOfCity;
@Persistent
@Element(dependent = "true")
private ArrayList<NumberBean> numbers;
}
This is the numberBean. it has a collection of owners.
@PersistenceCapable(detachable = "true")
@FetchGroup(name="fet_own", members={@Persistent(name="owners")})
public class NumberBean {
public NumberBean(String areaCode, String num) {
super();
this.areaCode = areaCode;
this.num = num;
this.owners = new ArrayList<OwnerBean>();
}
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String areaCode;
@Persistent
private String num;
}
This is the owner bean. It has no collections
@PersistenceCapable(detachable = "true")
public class OwnerBean {
public OwnerBean(String fname, String lname) {
super();
this.fname = fname;
this.lname = lname;
}
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String fname;
@Persistent
private String lname;
}
Now i am fetching, detaching and setting the numebrs collection to a brand new collection. But in the result i see that directory has the old numbers and the new numbers
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.getFetchPlan().addGroup("fet_own").addGroup("fet_num");
pm.getFetchPlan().setMaxFetchDepth(-1);
pm.getFetchPlan().setDetachmentOptions(pm.getFetchPlan().DETACH_LOAD_FIELDS);
pm.setDetachAllOnCommit(true);
DirectoryBean dirBeanInstance=null;
try{
Key k = KeyFactory.createKey(DirectoryBean.class.getSimpleName(), "lake City");
dirBeanInstance = pm.getObjectById(DirectoryBean.class,k);
dirBeanInstance.getNumbers().size();
dirBeanInstance.getNumbers().get(0).getOwners().size();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
pm.close();
}
ArrayList<NumberBean> newNumBeans = new ArrayList<NumberBean>();
newNumBeans.add(new NumberBean("555", "7777777"));
dirBeanInstance.setNumbers(newNumBeans);
pm = PMF.get().getPersistenceManager();
try{
pm.makePersistent(dirBeanInstance);
}catch(Exception e)
{
e.printStackTrace();
}finally
{
pm.close();
}