Question

I am using embeddable version of db4o 8.1. The issue is when I retrieve an object and just call set of a property, it seems to be persisting the value in cache and subsequent retrieval gives me the same reference even when I try to retrieve by ID.

The following code is used to retrieve the object from db.

public Customer retrieveCustomer(final String id) {
    ObjectContainer db = getDataSource();
    Customer customer = null;
    try {
        List<Customer> result = db.query(new Predicate<Customer>() {
            private static final long serialVersionUID = 1L;

            public boolean match(Customer pilot) {
                return pilot.getId().equalsIgnoreCase(id);
            }
        });
        if (result.size() > 0) {
            customer = result.get(0);
        }
    }
    catch (Exception e) {
        logger.error("Internal db failed to retrieve the object.", e);
    }
    return customer;
}

And somewhere in code I do setName("xyz"); from original value of "abc" and I don't do commit anywhere.

customer.setName("xyz"); // no commit or store

Everything is fine here but when the object is retrieved again from db it gives me xyz instead of "abc" as i didn't store or commit the previous object.

When I restart the server ( close and open the db ) the old value is restored

Please help.

Was it helpful?

Solution

That's a pretty common mistake for db4o newcomers :)

The problem is that, once retrieved in a session, db4o will keep a reference to the object (that's how it figure it out whenever a Store() is indeed a store or an update); so the second time you fetch the object from db, db4o will find the cached one and return it (you can read more about this, and other concepts, here).

The solution? Depends on your needs, but you could:

  • Make a clone of the returned object and update this clone
  • Open multiple sessions with the database (db4o has some optimizations for embedded clients).

If you are new to db4o, I recommend reading this documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top