injektilo injektilo - 27 days ago 7
Android Question

android greendao update only specific fields in entity

i have been searching for a while for a solution to my problem without success.

I have an application in which I receive information for a particular entity in my database from different services, so I am using greenDAOs insertOrReplace methods so whenever the entity already exists in my DB it gets updated instead of recreated.

So far so good.

The problem is.. let's say for example sake my entity is called User, with fields id, title, and displayName.

So in the first call I get a JSON object containing a user with only its id and title fields, so I insert it into the DB and naturally the displayName gets inserted as NULL.

Afterwards from another service I get another JSON containing the same user (same id field), but it comes with the displayName as well, but doesn't include the title info at all.

So whenever I run the insertOrReplace on the DAO object automatically generated by greenDAO, the user gets updated but as the title info was not present, when it gets updated the title field gets reset to NULL, so I end up losing data.

Unfortunately I am unable to change the data being returned from the services, and haven't been able to fix this issue. I find it hard to believe there is no easy way to tell the DAO object to update only certain fields and no all of them.

I was looking at the code generated by greenDAO and in the dao objects generated there is a bindValues method which gets called before the query gets executed, and apparently it filters out the NULL properties from the object, but either way it gets updated with the NULL value.

I was able to come up with some sort of fix by modifying the final dao object being generated by adding some methods from the parent class, but I don't think this is a good solution because I would have to do this for all the dao objects. (I know it's possible to define a custom superclass but this only applies for the entity object and not the DAO one).

I would really appreciate if someone has any idea on how I could resolve this, and sorry for the long explanation, I just wanted to be clear on my issue.

Thanks.

Answer

First of all: I wouldn't tamper with the generated code unless you really know what you are doing. Modifications may have effects on caches and data-integrity.

Generally you are following this (insert-or)-update-approach if you are using a ORM-Framework (like greendao):

  1. Try to get the entity, that you want to modify from the db (maybe it is already in cache, so this may not be a real database operation)
  2. If you don't have such an entity: create it
  3. Modify the entity according to your needs
  4. Insert or Update it in database (in greendao you would use insertOrReplace)