GreenDao, disable inner cache get() - android

I'm using GreenDao and creating a core function that help you to update some values of an entity, and if the entity is not in the database then it also inserting it. The problem is that I'm always getting the cached copy of the entity, I know that GreenDao manage some simple cache and I would like to have the ability bypass it. does anyone knows how I can query right from the database?
This doesn't work
.Dao().queryBuilder().where(comDao.Properties.Id.eq(id)).build().listLazyUncached();

GreenDao indeed has Inner caching mechanism in its daoCore.jar sources.
You can disable the caching easily by searching for the code that put() and get() entities from the cache.
which is a: HashMap<? extends AbstractDao>.
Then generate MyDaoCore.jar and add it to your project.
Secondly, in order to update or insert and entity (without replacing it entirely) you need to implement the following pseudo code. I'm sorry that I'm not adding the actual code, I solved it long time ago.
public void insertOrUpdate(List<? extends AbstractDao> entities){
List<Entity> toInsert;
List<Entity> toUpdate;
for (Entity e : entities)
{
if( e.inDatabase() )
toUpdate.add(e);
else
toInsert.add(e);
}
Dao.updateAll(toUpdate);
Dao.insertAll(toInsert);
}
Edit 1:
You can use IN statement in order to get all the ids of an entity in only one query like this:
.where(Dao.Properties.Id.in(ids)).build().list();

Related

Class doesn't exist in current schema after being added to migration

I've been struggling performing a simple migration. What I just want to achieve is add a new Class in realm.
The code below is inside a method that is called inside onCreate.
Realm.init(this)
val config = RealmConfiguration.Builder()
.name("db_name")
.schemaVersion(5L)
.migration { realm, oldVersion, newVersion ->
val schema = realm.schema
var _oldVersion = oldVersion
if (_oldVersion == 4L) {
if (schema.contains(XModel::class.java.simpleName))
schema.remove(XModel::class.java.simpleName)
if (!schema.contains(XModel::class.java.simpleName))
schema.create(XModel::class.java.simpleName)
.addField(XModel::id.name, Long::class.javaPrimitiveType,
FieldAttribute.PRIMARY_KEY)
...
.addField(XModel::N.name, Int::class.javaPrimitiveType)
_oldVersion += 1
}
}
.build()
Realm.setDefaultConfiguration(config)
As what the title suggest, the new class in the schema was created inside the migration object, but when I try to access it in other parts of the application using a realm query or a simple call to schema.get("XModel") it will throw an error XModel doesn't exist in current schema. Any comment will really help. Thank you...
Edit:
Additional information. I have 2 realm objects, each are in different android modules, one module is dependent to the other. I somehow have some progress, now Im a bit confuse, do I need to declare 2 configurations? Then it would mean 2 realm instance? How to switch from both, I want to merge them into 1 realm.
Edit2:
Another clarification about realm. If you have 2 android modules, each of them using realm, will they have different realm even if in the realm configuration they have the same name?
Background
I want to give you a background of what im doing because I think its needed to fully understand my case.
Originally I only have one module, but then after refactoring and also because of future apps to be develop, I need to pull out the common classes from the existing module and put it in a separate lower-level module that the future apps can depend on. This new lower-level module will also be responsible for most of the data layer, so realm was transferred to this module. But I can't just ignore the realm of the existing app because some users might already populated it, and I need to transfer those data to the new database.

How to add new items to a pagedList backed by Room?

I am using Network + Database for pagination in my app. I have 2 model classes that extends same types. Only one type of model is backed by a Room database. I want to inject other model class in between the PagedList based on some business rules. When I try to do that by using mapByPage function on DataSource.Factory returned by Room. The paging library is throwing IllegalStateExeception with message that size has changed. How do I go about implementing this case?
I think the size of the list needs to be the same. I tried to look for official documentation but I couldn't find it.
But found this comment
https://stackoverflow.com/a/49666673/430652

What is the correct way to initialize data in a lookup table using DBFlow?

I am trying to implement DBFlow for the first time and I think I might just not get it. I am not an advanced Android developer, but I have created a few apps. In the past, I would just create a "database" object that extends SQLiteOpenHelper, then override the callback methods.
In onCreate, once all of the tables have been created, I would populate any lookup data with a hard-coded SQL string: db.execSQL(Interface.INSERT_SQL_STRING);. Because I'm lazy, in onUpgrade() and onDowngrade(), I would just DROP the tables and call onCreate(db);.
I have read through the migrations documentation, which not only seems to be outdated syntactically because "database =" has been changed to "databaseName =" in the annotation, but also makes no mention of migrating from no database to version "initial". I found an issue that claims that migration 0 can be used for this purpose, but I cannot get any migrations to work at this point.
Any help would be greatly appreciated. The project is # Github.
The answer below is correct, but I believe that this Answer and Question will soon be "deprecated" along with most third-part ORMs. Google's new Room Persistence Library (Yigit's Talk) will be preferred in most cases. Although DBFlow will certainly carry on (Thank You Andrew) in many projects, here is a good place to re-direct people to the newest "best practice" because this particular question was/is geared for those new to DBFlow.
The correct way to initialize the database (akin to the SQLiteOpenHelper's onCreate(db) callback is to create a Migration object that extends BaseMigration with the version=0, then add the following to the onCreate() in the Application class (or wherever you are doing the DBFlow initialization):
FlowManager.init(new FlowConfig.Builder(this).build());
FlowManager.getDatabase(BracketsDatabase.NAME).getWritableDatabase();
In the Migration Class, you override the migrate() and then you can use the Transaction manager to initialize lookup data or other initial database content.
Migration Class:
#Migration(version = 0, database = BracketsDatabase.class)
public class DatabaseInit extends BaseMigration {
private static final String TAG = "classTag";
#Override
public void migrate(DatabaseWrapper database) {
Log.d(TAG, "Init Data...");
populateMethodOne();
populateMethodTwo();
populateMethodThree();
Log.d(TAG, "Data Initialized");
}
To populate the data, use your models to create the records and the Transaction Manager to save the models via FlowManager.getDatabase(AppDatabase.class).getTransactionManager()
.getSaveQueue().addAll(models);
To initialize data in DBFlow all you have to do is create a class for your object models that extends BaseModel and use the #Table annotation for the class.
Then create some objects of that class and call .save() on them.
You can check the examples in the library's documentation.

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.

ORMLite OpenHelper DAO caching in DaoManager?

So I have a custom subclass of OrmLiteSqliteOpenHelper. I want to use the ObjectCache interface to make sure I have identity-mapping from DB rows to in-memory objects, so I override getDao(...) as:
#Override
public <D extends Dao<T, ?>, T> D getDao(Class<T> arg0) throws SQLException {
D dao = super.getDao(arg0);
if (dao.getObjectCache() == null && !UNCACHED_CLASSES.contains(arg0))
dao.setObjectCache(InsightOpenHelperManager.sharedCache());
return dao;
}
My understanding is that super.getDao(Class<T> clazz) is basically doing a call to DaoManager.createDao(this.getConnectionSource(),clazz) behind the scenes, which should find a cached DAO if one exists. However...
final DatabaseHelper helpy = CustomOpenHelperManager.getHelper(StoreDatabaseHelper.class);
final CoreDao<Store, Integer> storeDao = helpy.getDao(Store.class);
DaoManager.registerDao(helpy.getConnectionSource(), storeDao);
final Dao<Store,Integer> testDao = DaoManager.createDao(helpy.getConnectionSource(), Store.class);
I would expect that (even w/o the registerDao(...) call) storeDao and testDao should be references to the same object. I see this in the Eclipse debugger, however:
Also, testDao's object cache is null.
Am I doing something wrong here? Is this a bug?
I do have a custom helper manager, but only because I needed to manage several databases. It's just a hashmap of Class<? extends DatabaseHelper> keys to instances.
The reason I need my DAO cached is that I have several foreign collections that are eager and are being loaded by internally-generated DAOs that are not using my global cache and thus are being re-created independently for each collection.
As I was writing this up, I thought I could just have my overridden helpy.getDao(...) call through to DaoManager.createDao(...), but that results in the same thing: I still get a different DAO on the second call to createDao(...). This seems to me to be totally against the docs for DaoManager.
First, I thought it looked like registerDao(...) may be the culprit:
public static synchronized void registerDao(ConnectionSource connectionSource, Dao<?, ?> dao) {
if (connectionSource == null) {
throw new IllegalArgumentException("connectionSource argument cannot be null");
}
if (dao instanceof BaseDaoImpl) {
DatabaseTableConfig<?> tableConfig = ((BaseDaoImpl<?, ?>) dao).getTableConfig();
if (tableConfig != null) {
tableMap.put(new TableConfigConnectionSource(connectionSource, tableConfig), dao);
return;
}
}
classMap.put(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);
}
That return on line 230 of the source for DaoManager prevents the classMap from being updated (since I'm using the pregenerated config files?). When my code hits the second create call, it looks at the classMap first, and somehow (against my better understanding) finds a different copy of the DAO living there. Which is super weird, because stepping through the first create, I watched the classMap be initialized.
But where would a second DAO possibly come from?
Looking forward to Gray's insight! :-)
As #Ben mentioned, there is some internal DAO creation which is screwing things up but I think he may have uncovered a bug.
Under Android, ORMLite tries to use some magic reflection to build the DAOs given the horrible reflection performance under all but the most recent Android OS versions. Whenever the user asks for the DAO for class Store (for example), the magic reflection fu is creating one DAO but internally it is using another one. I've created the follow bug:
https://sourceforge.net/tracker/?func=detail&aid=3487674&group_id=297653&atid=1255989
I changed the way the DAOs get created to do a better job of using the reflection output. The changes were pushed out in the 4.34. This release revamps (and simplifies) the internal DAO creation and caching. It should fix the issue.
http://ormlite.com/releases/
Just kidding. Looks like what may be happening is that my Store object DAO initialization is creating DAO's for foreign connections (that I set to foreignAutoRefresh) and then recursively creating another DAO for itself (since the DAO creation that started this has not completed, and thus has yet to be registered w/ the DaoManager).
Looks like this has to do w/ the recursion noted in BaseDaoImpl.initialize().
I'm getting Inception flashbacks just looking at this.

Categories

Resources