agrosner / DBFlow

A blazing fast, powerful, and very simple ORM android database library that writes database code for you.
MIT License
4.87k stars 598 forks source link

Insert multiple objects in database create time #666

Closed gorodechnyj closed 8 years ago

gorodechnyj commented 8 years ago

How do I load my fixtures from database on create time? I tried to extend FlowSQLiteOpenHelper and do some Model.insert() calls in onCreate method. Obviously this leads to looping getDatabase() calls.

After that I have tried getting insert script from adapter, and couldn't get one for the same reason. After that I have tried to get content values and insert them through native db.insert() call. No success, since to get ContentValues I need to get instance of adapter class as well.

Of course I can load my data in Application class or on login screen and put SharedPreferences flag indicating data has been loaded, but DBFlow really needs a simple way to load fixtures. One will not simply generate SQLite db file and use it as a holder for initial data since this way tests and development process becomes very complicated.

I suggest you a feature: use json file or series of files, containing initial values for tables, parse them in SQLiteOpenHelper and insert them after database is created. Or one can put those files in assets and point to them in @Table annotation.

agrosner commented 8 years ago

did you try a @Migration where version is 0?

gorodechnyj commented 8 years ago

This didn't help since I'm saving objects with Model.save()

kenneth2008 commented 8 years ago

I think what you need is bulk insert or bulk update? If yes, the answer is transaction.

agrosner commented 8 years ago

In a migration, you cannot recursively access the database object. So you need to pass in a DatabaseWrapper, however this does not exist for Model. In develop (will be in beta4). you can (for each model):

  DatabaseStatement insertStatement = modelAdapter.getInsertStatement(databaseWrapper);
// for each model in list
        adapter.bindToInsertStatement(insertStatement, model);
        long id = insertStatement.executeInsert();
        adapter.updateAutoIncrement(model, id);
        notifyModelChanged(model, adapter, modelAdapter, Action.INSERT);

Which will provide the insert you need in this scenario.

gorodechnyj commented 8 years ago

Will be waiting for it, thx

agrosner commented 8 years ago

in beta 4 and in develop you can use the corresponding ModelAdapter to not recurse the DB:


final ModelAdapter<SomeModel> modelAdapter = FlowManager.getModelAdapter(SomeModel.class);

// for each in a transaction
    modelAdapter.save(model, databaseWrapper);
mtaheri commented 8 years ago

Hi I m new in dbflow , how can i create database wrapper ?