greendao delete from db and session - android

I'm using greendao for a android project and wanted to know how to properly delete and object from the db and from the session cache. Currently I do the following to delete from the db:
ChatDao chatDao = daoSession.getChatDao();
chatDao.queryBuilder().buildDelete().executeDeleteWithoutDetachingEntities();
However as the method name and documentation state this may leave stale objects in the session cache, how can I remove the objects from there too?

In order to clear cached objects in your DaoSession use this call:
DaoSession.clear();
It will clear all objects in your session identity scope.

As Anatoliy described, you can use DaoSession.clear(). However, it will clear all all objects from the session. If you want to avoid that, you have to execute a regular query and delete the result entities (for example with deleteInTx).

Related

firebase persist data with circular reference

I've a simple data that i want to persist on firebase.
This data is a domain class for my relational model (i started with a relational model and now im deciding whenever or not migrate to firebase, but for awhile im working with both... or trying to)
To persist a new instance if my class on firebase i need to do:
Map<String, Object> firebase = new HashMap<String, Object>();
firebase.put("raffleDate", this.giveaway.getRaffleDate());
firebase.put("thumbnailUrl", this.giveaway.getThumbnailUrl());
firebase.put("mustFollowList", this.giveaway.getMustFollowList());
firebase.put("owner", this.giveaway.getOwner());
firebase.put("amountFriendsToIndicate", this.giveaway.getAmountFriendsToIndicate());
firebase.put("mediaId", this.giveaway.getMediaId());
((App) getApplication()).getFirebase().child("giveaways").child(this.giveaway.getMediaId()).setValue(firebase);
because besides these fields Giveaway has one last other field which has a circular reference to itself
#ToMany(referencedJoinProperty = "raffle")
#Expose(deserialize = false, serialize = false)
private List<UserOnGiveaway> attendantsTickets;
This field maps the relatioship between user and its giveaways, UserOnGiveaway class has a reference to User and Giveaway so when i try to persist i get a very long non compreensive error that I can just guess is due some stackoverflow because of the circular reference
The thing is I DONT REALLY CARE ABOUT PERSISTING THIS FIELD, in my actual "hybrid" archtecture i'm using firebase only to persist data shared among users, individual user data is being stored locally on android sqlite
So i would like to know is there any way i can annotate this field to force firebase ignore it?
or is there any parameter is can set on firebase call to do it?
PLEASE do not suggest transient as it will also affect my ORM
PLEASE2 do not suggest changes on domain since i'm giving a try to firebase i wont make any structural changes before decide for it.
thanks
You can use the #Exclude annotation on a field or getter/setter method to omit it from serialization with the Firebase SDK.

Unexpected entity related to newly created

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?
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.

Transactions in GreenDao

I'm using GreenDao to store a lot of data, coming from a REST service.
A lot of my entities are connected with relations.
Everything works great, but tomorrow I have to implement a rocksolid workflow.
When I load my data I have to check if an error occurs.
If so, I have to make sure nothing is stored in the SQLite DB.
Normally I would work with transactions and rollback in case of an exception,
otherwise commit to the db.
For now I just use insertordelete to save an entity, everytime I created an object.
What would be the way to implement this?
On inserts and updates Greendao checks if there is a ongoing transaction. If that is the case greendao will not start a new transaction.
So the only thing to do is to start a transaction on your database and commit/rollback after your work is done or you notice an error. All inserts and updates will be in the same transaction which has benefits concerning data consistency and also on performance, since greendao will start new transactions with commit/rollback for every insert and update operation.
Summarized you can use code like this:
SQLiteDatabase db = dao.getDatabase();
db.beginTransaction();
try {
// do all your inserts and so on here.
db.setTransactionSuccessful();
} catch (Exception ex) {
} finally {
db.endTransaction();
}
I also tweaked my greendao a bit so that it doesn't cache inserted objects to get further performance and memoryusage benefits (since I insert a lot of data once and I only use very few data during runtime depending on user input). See this post.

ActiveAndroid: lock records for updates?

In ActiveRecord, there's a concept of locking records for updates to ensure that a stale object doesn't get saved to the database.
Is there equivalent functionality in ActiveAndroid? If so, is there a link showing how to do it? If not, what would be the best approach to prevent stale objects from getting saved to the db?
ActiveAndroid has a concept of beginTransaction() and endTransaction() which basically are similar to the locking record concept in activeRecord. By using the beginTransaction() you ensure that while any changes being made to a method or data is being accessed, no other object can interfere with the process. Once the endTransaction() is executed, the method is "unlocked" and other objects can start to interact with it.
I don't know the answer, but what I am doing is, declaring an unique field in my model class, and onUniqueConflict replacing the old record with the new one.
#Column(name = "userId", notNull = true,unique = true,onUniqueConflict = Column.ConflictAction.REPLACE)
private String userId;

GreenDao reload an object when using IdentityScope != None

I have the case that I operate on some object I got from greenDao and in some cases I have to revert the changes. I only got this to work with IdentityScope.None - with some IdentityScope I found no way to do that - even refresh() which sounded promising was not bringing back the data from the database. Is there any way to do this with a IdentityScope?
The refresh(entity) method of a DAO does reload all entity values from the database. However, it operates on a single entity, not on a tree of entities.

Categories

Resources