greenDAO

3,230 views

Published on

Published in: Technology
  • Be the first to comment

greenDAO

  1. 1. greenDAOKewang
  2. 2. Agenda● SQL syntax● SQLite @ Android● ORM● greenDAO
  3. 3. SQL syntax
  4. 4. SELECT● SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName● SELECT * FROM Persons WHERE LastName BETWEEN Hansen AND Pettersen● SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders GROUP BY Customer,OrderDate
  5. 5. INSERT● INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, Tjessem, Jakob)● INSERT INTO Persons VALUES (4,Nilsen, Johan, Bakken 2, Stavanger)
  6. 6. UPDATE● UPDATE Persons SET Address=Nissestien 67, City=Sandnes WHERE LastName=Tjessem AND FirstName=Jakob● UPDATE Persons SET Address=Nissestien 67, City=Sandnes
  7. 7. DELETE● DELETE FROM Persons WHERE LastName=Tjessem AND FirstName=Jakob
  8. 8. SQLite @ Android
  9. 9. 4 components● SQLiteOpenHelper● SQLiteDatabase● SQLiteQueryBuilder● Cursor
  10. 10. SQLiteOpenHelperA helper class to manage databasecreation and version management.
  11. 11. SQLiteDatabase + SQLiteQueryBuilder delete * 1 append * 3 insert * 3 replace(update) * 4 open * 5 query * 15
  12. 12. Oh my god, Im a professional DBA!!!
  13. 13. Never mind, we have...... execSQL * 2db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primarykey autoincrement, name varchar(20), age INTEGER)");
  14. 14. and rawQuery * 4 db.rawQuery("select count(*) from person", null);
  15. 15. Cursor Recordsets returned by a query
  16. 16. Cursor getDataType * 16 movePosition * 6 isXXX * 6
  17. 17. Sample code - Controllerdatasource = new CommentsDataSource(this);datasource.open();List<Comment> values = datasource.getAllComments();ArrayAdapter<Comment> adapter = newArrayAdapter<Comment>(this,android.R.layout.simple_list_item_1, values); open
  18. 18. Sample code - ControllerString[] comments = new String[] { "Cool", "Very nice","Hate it" };int nextInt = new Random().nextInt(3);comment = datasource.createComment(comments[nextInt]);adapter.add(comment); insert
  19. 19. Sample code - Controller if (getListAdapter().getCount() > 0) { comment = (Comment) getListAdapter().getItem(0); datasource.deleteComment(comment); adapter.remove(comment); } delete
  20. 20. Sample code - Model@Overridepublic void onCreate(SQLiteDatabase database) { database.execSQL("create table " + TABLE_COMMENTS +"(" + COLUMN_ID + " integer primary key autoincrement, "+ COLUMN_COMMENT + " text not null);");}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS); onCreate(db);}
  21. 21. Sample code - Modelpublic Comment createComment(String comment) { ContentValues values = new ContentValues(); values.put("comment", comment); long id = database.insert("comments", null, values); Cursor cursor = database.query("comments", allColumns,"_id" + " = " + id, null, null, null, null); cursor.moveToFirst(); cursor.close(); return cursorToComment(cursor);}
  22. 22. Sample code - Modelpublic void deleteComment(Comment comment) { long id = comment.getId(); database.delete("comments", "_id" + " = " + id, null);}
  23. 23. Sample code - Model private Comment cursorToComment(Cursor cursor) { Comment comment = new Comment(); comment.setId(cursor.getLong(0)); comment.setComment(cursor.getString(1)); return comment; }
  24. 24. Sample code - Modelpublic List<Comment> getAllComments() { List<Comment> comments = new ArrayList<Comment>(); Cursor cursor = database.query("comments", allColumns,null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { comments.add(cursorToComment(cursor)); cursor.moveToNext(); } cursor.close(); return comments;}
  25. 25. No better choice ?
  26. 26. ORMObject-relational mapping
  27. 27. Record maps to Java Object
  28. 28. Rails sample
  29. 29. We use SQLite @ Android OrmLite greenDAO
  30. 30. greenDAO
  31. 31. Architecture
  32. 32. Structure
  33. 33. How to use...private void initDatabase() { helper = new DaoMaster.DevOpenHelper(this, NAME, null); master = new DaoMaster(helper.getWritableDatabase()); session = master.newSession(); cityDao = session.getCityDao(); townDao = session.getTownDao(); storeDao = session.getStoreDao();}
  34. 34. How to use... cityDao.insert(new City(1L, "台北市")); storeDao._queryTown_Stores(townId).isEmpty()town =townDao.queryBuilder().where(TownDao.Properties.Name.eq("新莊區"), TownDao.Properties.CityId.eq(5)).unique();
  35. 35. At first, generate code to use it.public static void main(String[] args) { schema = new Schema(4, "tw.kewang.smile319.model"); addCity(); addTown(); addStore(); new DaoGenerator().generateAll(schema, "../Prj/src-gen");}
  36. 36. At first, generate code to use it.private static void addTown() { Entity town = schema.addEntity("Town"); town.addIdProperty().columnName("id"); town.addStringProperty("name").notNull(); town.addDoubleProperty("latitude"); town.addDoubleProperty("longitude"); Property cityId =town.addLongProperty("cityId").notNull().getProperty(); ToMany cityToTowns = city.addToMany(town, cityId); cityToTowns.setName("towns");}
  37. 37. What is generator ?
  38. 38. Generator contains...● A schema at least● A schema has many entities (models)● A entity has many property (data type, not null, autoincrement, index......etc.)● 2 entities have a relationship (optional) ● Project has a leader ● Leader belongs to a project
  39. 39. QueryBuilder● whereXXX● joinXXX● orderXXX● listXXX● uniqueXXX● or, and● limit, offset, count
  40. 40. FAQ
  41. 41. 1. Why use generator ?
  42. 42. Typically, annotation & reflection BUT1.cant compiler check2.reflection is very slow @ Android
  43. 43. 2. Why use greenDAO ?
  44. 44. Speed up !1.generator instead of reflection2.refine SQLiteCursor3.custom LongHashMap @ LUT
  45. 45. 3. What about OrmLite ?
  46. 46. References● http://greendao-orm.com/● https://github.com/greenrobot/greenDAO● http://www.slideshare.net/droidcon/green-dao
  47. 47. 49

×