orientdb icon indicating copy to clipboard operation
orientdb copied to clipboard

Object DB: Cannot reliably remove objects from EMBEDDEDLIST property

Open dxxr opened this issue 12 years ago • 1 comments

Orient DB v1.7

let's assume an object Foo with a List<Bar> property stored in the database as an EMBEDDEDLIST. (code below)

In this case the java.util.List.remove(Object o) method is not reliable, especially when the Foo is reloaded from another database connection so the document/object cache misses and it is a truely new instance.

public class Foo {
    private Integer id;
    private List<Bar> list;

    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public List<Bar> getList() { return list; }
    public void setList(List<Bar> list) { this.list = list; }
}

public class Bar {
    private Integer id;

    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        Integer id = getId();  // call getter for proxy
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Bar))
            return false;
        Bar other = (Bar) obj;
        if (!Objects.equals(this.getId(), other.getId())) // call getter for proxy
            return false;
        return true;
    }
}
private void testRemove() {
    Bar bar;
    List<Bar> list;
    // load a Foo and one of its Bar's
    try (OObjectDatabaseTx db = pool.acquire()) {
        List<Foo> rs = db.query(new OSQLSynchQuery<>("SELECT FROM Foo WHERE id = ?"), 1);
        Foo foo = rs.get(0);
        bar = foo.getList().get(0);
    }
    // load a new instance of the same Foo
    try (OObjectDatabaseTx db = pool.acquire()) {
        List<Foo> rs = db.query(new OSQLSynchQuery<>("SELECT FROM Foo WHERE id = ?"), 1);
        Foo foo = rs.get(0);
        list = foo.getList();
        // try to find / remove the old Bar from the new list ==> does NOT work
        System.out.println(list.indexOf(bar) + " / " + list.size());
        System.out.println(list.remove(bar));
        System.out.println(list.indexOf(bar) + " / " + list.size());
        // compare the old and new Bar's ==> TRUE
        System.out.println(bar.equals(list.get(0)));
    }
}

dxxr avatar Jun 03 '14 09:06 dxxr

As a workaround I currently dump all elements from the Embedded List into a newly created ArrayList, remove the element in question from that list and then replace the whole Embedded List with the new one.

dxxr avatar Jun 17 '14 13:06 dxxr