+ All Categories
Home > Technology > greenDAO

greenDAO

Date post: 06-May-2015
Category:
Upload: mu-chun-wang
View: 1,661 times
Download: 2 times
Share this document with a friend
49
greenDAO Kewang
Transcript
Page 1: greenDAO

greenDAO

Kewang

Page 2: greenDAO

Agenda

● SQL syntax● SQLite @ Android● ORM● greenDAO

Page 3: greenDAO

SQL syntax

Page 4: greenDAO

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

Page 5: greenDAO

INSERT

● INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')

● INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')

Page 6: greenDAO

UPDATE

● UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='Jakob'

● UPDATE Persons SET Address='Nissestien 67', City='Sandnes'

Page 7: greenDAO

DELETE

● DELETE FROM Persons WHERE LastName='Tjessem' AND FirstName='Jakob'

Page 8: greenDAO

SQLite @ Android

Page 9: greenDAO

4 components

● SQLiteOpenHelper● SQLiteDatabase● SQLiteQueryBuilder● Cursor

Page 10: greenDAO

SQLiteOpenHelper

A helper class to manage database creation and version management.

Page 11: greenDAO

SQLiteDatabase + SQLiteQueryBuilder

delete * 1append * 3insert * 3replace(update) * 4open * 5query * 15

Page 12: greenDAO

Oh my god, I'm a professional DBA!!!

Page 13: greenDAO

Never mind, we have......

execSQL * 2db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)");

Page 14: greenDAO

and

rawQuery * 4db.rawQuery("select count(*) from person", null);

Page 15: greenDAO

Cursor

Recordsets returned by a query

Page 16: greenDAO

Cursor

getDataType * 16movePosition * 6isXXX * 6

Page 17: greenDAO

Sample code - Controller

datasource = new CommentsDataSource(this);

datasource.open();

List<Comment> values = datasource.getAllComments();ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);

open

Page 18: greenDAO

Sample code - Controller

String[] comments = new String[] { "Cool", "Very nice", "Hate it" };int nextInt = new Random().nextInt(3);

comment = datasource.createComment(comments[nextInt]);

adapter.add(comment);

insert

Page 19: greenDAO

Sample code - Controller

if (getListAdapter().getCount() > 0) { comment = (Comment) getListAdapter().getItem(0);

datasource.deleteComment(comment); adapter.remove(comment);}

delete

Page 20: greenDAO

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);}

Page 21: greenDAO

Sample code - Model

public 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);}

Page 22: greenDAO

Sample code - Model

public void deleteComment(Comment comment) { long id = comment.getId();

database.delete("comments", "_id" + " = " + id, null);}

Page 23: greenDAO

Sample code - Model

private Comment cursorToComment(Cursor cursor) { Comment comment = new Comment();

comment.setId(cursor.getLong(0)); comment.setComment(cursor.getString(1));

return comment;}

Page 24: greenDAO

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;}

Page 25: greenDAO

No better choice ?

Page 26: greenDAO

ORMObject-relational mapping

Page 27: greenDAO
Page 28: greenDAO

Record maps to Java Object

Page 29: greenDAO

Rails sample

Page 30: greenDAO

We use SQLite @ Android

OrmLitegreenDAO

Page 31: greenDAO

greenDAO

Page 32: greenDAO

Architecture

Page 33: greenDAO

Structure

Page 34: greenDAO

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();}

Page 35: greenDAO

How to use...

cityDao.insert(new City(1L, "台北市"));

town = townDao.queryBuilder().where(TownDao.Properties.Name.eq("新莊區"), TownDao.Properties.CityId.eq(5)).unique();

storeDao._queryTown_Stores(townId).isEmpty()

Page 36: greenDAO

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");}

Page 37: greenDAO

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");}

Page 38: greenDAO

What is generator ?

Page 39: greenDAO

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

Page 40: greenDAO

QueryBuilder

● whereXXX● joinXXX● orderXXX● listXXX● uniqueXXX● or, and● limit, offset, count

Page 41: greenDAO

FAQ

Page 42: greenDAO

1. Why use generator ?

Page 43: greenDAO

Typically, annotation & reflection

BUT1.can't compiler check2.reflection is very slow @ Android

Page 44: greenDAO

2. Why use greenDAO ?

Page 45: greenDAO

Speed up !1.generator instead of reflection2.refine SQLiteCursor3.custom LongHashMap @ LUT

Page 46: greenDAO

3. What about OrmLite ?

Page 47: greenDAO
Page 48: greenDAO

References

● http://greendao-orm.com/● https://github.com/greenrobot/greenDAO● http://www.slideshare.net/droidcon/green-dao

Page 49: greenDAO

49