O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

GreenDao Introduction

3.667 visualizações

Publicada em

GreenDao Introduction
For anyone want start integrate ORM.
It make easily sample to explain GreenDao benefit

https://vinta.ws/booch/?p=85

Publicada em: Software
  • Seja o primeiro a comentar

GreenDao Introduction

  1. 1. GreenDao 綠道 Heaton
  2. 2. Outline • Why GreenDao • Feature • Performance • How to getting start • How to use.
  3. 3. Why GreenDao • First . Some problem with DB Development. – No object orientation. – Data access sentence is low levely. – Always make same code to write SQL script. – Do you know SQL without 『||』. – I am stupid on SQL tuning • Second , it is faster than other ORM Lib.
  4. 4. It is popular?
  5. 5. Features • High Performance – CRD test. • ORM (Object relation mapping) – Code Generation – Read and write objects – CREATE TABLE done for you – Expressing Queries • Session cache • Setter ; getter • Create table “table_name” • Return List<Common>
  6. 6. Performance • Test case : – insert 10000 row – delete 10000 row – query 20000 row Test 1 Dao Content Provider Insert 1467 87268 (no transcation) Load 1608 9797 Delete 108 121 Test 2 Insert 662 87766 Load 1837 12282 delete 137 127
  7. 7. Benchmark • https://github.com/daj/android-orm- benchmark • Write 10000 • Read 10000
  8. 8. ORM Object/relation mapping (ORM)
  9. 9. A example for presentation • Implement a social data collector • “Leftpage” as table name for database “leftpageProvider.db” • Every row data as “CommonData” • Column has – ”DataID” as primary key – “Category” – “Provider” – “DisplayOrder”
  10. 10. Expressing Queries: What difference • SQL Query all – Cursor c = mContext.getContentResolver().query(uriLPagePr ovider , projection , selection, selection args, sort order ) ; • GreenDao Load all List<commonData> datas = CommonDataDao.loadAll();
  11. 11. Sqlite review • SQL Query – Provider equal facebook – Order by display order – Limit data count100 • Cursor c = getContentResolver() . query (uriLPageProvider , projection , selection, selection args, sort order ) ; (String ) selection : StorageField.Provider. + "=?" = (String[])selection args: {“facebook”}
  12. 12. Sort order • SQL Query – Provider equal facebook – Order by display order – Limit data count100 • Cursor c = getContentResolver() . query (uriLPageProvider , projection , selection, selection args, sort order ) ; (String ) Sort order: StorageField.Displayorder
  13. 13. More detail • SQL Query – Provider equal facebook – Order by display order – Limit data count100 • Cursor c = getContentResolver() . query (uriLPageProvider , projection , selection, selection args, sort order ) ; (String ) Sort order: “ ASC ” + StorageField.Displayorder + “ LIMIT ” + request
  14. 14. If you are sqlite master • SQL Query – Provider equal facebook – Order by display order – Limit data count100 • Select * from leftpage where Provider = ‘facebook’ order asc ‘displayorder’ limit ‘100’ • Then you also load cusor and save to data list
  15. 15. But in GreenDao • SQL Query – Provider equal facebook – Order by display order – Limit data count100 mCommonDataDao.queryBuilder() .where(Properties.Provider.eq(Provider.Facebook)) .orderAsc(Properties.DisplayOrder) .limit(100) .list();
  16. 16. HOW TO GETTING START Create module
  17. 17. How to getting start? First time is terrible
  18. 18. Create a module to gen greendao code • In module gradle – Add Gradle script – compile 'de.greenrobot:greendao-generator:1.3.1
  19. 19. Create main() in our case. public class GreenDao { public static void main(String[] args){ Schema schema = new Schema (1, "com.acer.android.leftpage.provider"); Entity commonData = schema.addEntity("commonData"); commonData.setTableName("LeftPage"); commonData.addLongProperty("DataID").primaryKey(); commonData.addStringProperty("Category"); commonData.addStringProperty("Provider"); commonData.addLongProperty(“DisplayOrder”); commonData.addContentProvider(); DaoGenerator generator = new DaoGenerator(); generator.generateAll (schema, "../AcerHome/LeftPage/src/main/java/");}
  20. 20. Compile and run to Auto gen Core classes DaoMaster DaoSeesion CommonDataDao CommonData
  21. 21. In CommonDataDao public static void createTable(SQLiteDatabase db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "'LeftPage' (" + // "'DataID' INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: DataID "'Category' TEXT," + // 1: Category "'Provider' TEXT," + // 2: Provider "'DisplayOrder' INTEGER DEFAULT -1," + // 3: DisplayOrder "'Bookmarked' INTEGER DEFAULT 0," + // 4: Bookmarked "'Deleted' INTEGER DEFAULT 0," + // 5: Deleted "'Score' REAL DEFAULT -1," + // 6: Score "'Keywords' TEXT DEFAULT NULL," + // 7: Keywords
  22. 22. CommonData content public Long getDataID() { return DataID; } public void setDataID(Long DataID) { this.DataID = DataID; } …… …… ……
  23. 23. Add it and start to use • In Used Project gradle – compile 'de.greenrobot:greendao:1.3.7'
  24. 24. HOW TO USE INSERT , DELETE , UPDATE,
  25. 25. Initial • DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context,”leftpage provider.db”); • DaoMaster master = new DaoMaster (helper.getDataBase()); • DaoSession session = master.newSession(); • CommonDataDao CommonDataDao= session.getCommonDataDao();
  26. 26. Query • Query with syntax – eq , notEq – ge , le , gt , lt – in , between – like • List<commonData> dataList = CommonDataDao.queryBuilder() .where(Properties.Provider.eq(Provider.Social)) .orderAsc(mCommonDataDao.Properties.DisplayOrder) .list();
  27. 27. Raw query SQLiteDatabase db = daoSession.getDatabase(); Cursor cursor = db.rawQuery("SELECT *FROM leftpage WHERE .....", null);
  28. 28. Insert • Insert: – CommonDataDao .insert(new CommonData(DATA_ID, arg1, arg2,x……)); • Bulk Insert – CommonDataDao .insertln(CommonDataList); – CommonDataDao.insertln(CommonData[]); • InsetOrReplace – CommonDataDao.insertOrReplaceln(CommonDataList) Note: DATA_ID usually is null .
  29. 29. Delete • Delete sentence – CommonDataDao.QueryBuilder() .where(Properties.Provider.eq(facebook)) .buildDelete() .executeDeleteWithoutDetachingEntities(); • Delete all – CommonDataDao.deleteAll();
  30. 30. Update • Update sentence – CommonDataDao.update(new CommonData(Data_ID , arg1 , arg2 , …….)); • Bulk Update – CommonDataDao.updateln(CommonDataList); – CommonDataDao.updateln(CommonData[]); Note: DATA_ID must assign what the row you want to update.
  31. 31. Thanks Reference: http://greendao-orm.com/features/ http://bng86.gitbooks.io/android-third-party- /content/greendao.html http://www.slideshare.net/SmileeYang/greendao- 43892958?qid=b95e0f35-a323-4930-8e8a- d0e298a1eb10&v=qf1&b=&from_search=1 http://www.slideshare.net/ssuser8674c1/green-dao- 50914708?qid=b95e0f35-a323-4930-8e8a- d0e298a1eb10&v=qf1&b=&from_search=5
  32. 32. Something here AsyncSession asyncSession = DBHelper.getInstance(this).getAsyncSession(); asyncSession.insert( new CommonData(null, …, …));

×