Unexpected entity related to newly created

59 Views Asked by At

In my Android application I am using GreenDao as an orm.

I have two tables: A and B. Table B has foreign key to table A. A entities can execute getBList() method and B entities can execute getA() method.

When I started to remove some A entities with connected B entities from database I noted strange behavior. Now some of newly created A entities have connected B entities, but there is no connecting in code:

A a = new A();
// setting some simple a fields, nothing with Bs
aDao.create(a);
a.getBList(); // not empty list

Does anybody know what can cause such behavior and how to fix it?

1

There are 1 best solutions below

0
On

This is from the greenDao website:

Resolving and Updating To-Many Relations

To-many relations are resolved lazily on the first request. After that, the related entities are cached in the source entity inside a List object. Subsequent calls to the get method of the relation do not query the database.

Note that updating to-many relations require some additional work. Because to-many lists are cached, they are not updated when related entities are added to the database. The following code illustrates the behavior:

List orders1 = customer.getOrders();
int size1 = orders1.size();

Order order = new Order();
order.setCustomerId(customer.getId());
daoSession.insert(order);

Listorders2 = customer.getOrders();
// size1 == orders2.size(); // NOT updated
// orders1 == orders2; // SAME list object

Likewise, you can delete related entities:

List orders = customer.getOrders(); daoSession.delete(newOrder);
orders.remove(newOrder);

Sometimes, it may be cumbersome or even impossible to update all to-many relations manually after related entities were added or removed. To the rescue, greenDAO has reset methods to clear the cached list. If a to-many relation may have changed potentially, you can force greenDAO to reload the list of related entities:

customer.resetOrders();
List orders2 = customer.getOrders();

Try to reset your relations when you add or remove elements.