SlideShare ist ein Scribd-Unternehmen logo
1 von 49
Downloaden Sie, um offline zu lesen
greenDAO

Kewang
Agenda
●   SQL syntax
●   SQLite @ Android
●   ORM
●   greenDAO
SQL syntax
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
INSERT
●   INSERT INTO Persons (P_Id, LastName, FirstName)
    VALUES (5, 'Tjessem', 'Jakob')
●   INSERT INTO Persons VALUES (4,'Nilsen', 'Johan',
    'Bakken 2', 'Stavanger')
UPDATE
●   UPDATE Persons SET Address='Nissestien 67',
    City='Sandnes' WHERE LastName='Tjessem' AND
    FirstName='Jakob'
●   UPDATE Persons SET Address='Nissestien 67',
    City='Sandnes'
DELETE
●   DELETE FROM Persons WHERE
    LastName='Tjessem' AND FirstName='Jakob'
SQLite @ Android
4 components
●   SQLiteOpenHelper
●   SQLiteDatabase
●   SQLiteQueryBuilder
●   Cursor
SQLiteOpenHelper



A helper class to manage database
creation and version management.
SQLiteDatabase + SQLiteQueryBuilder


       delete * 1
       append * 3
       insert * 3
       replace(update) * 4
       open * 5
       query * 15
Oh my god, I'm a professional DBA!!!
Never mind, we have......



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



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




 Recordsets returned by a query
Cursor



         getDataType * 16
         movePosition * 6
         isXXX * 6
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
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
Sample code - Controller


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

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


                               delete
Sample code - Model

@Override
public void onCreate(SQLiteDatabase database) {
  database.execSQL("create table " + TABLE_COMMENTS +
"(" + COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_COMMENT + " text not null);");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
  db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);

    onCreate(db);
}
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);
}
Sample code - Model


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

    database.delete("comments", "_id" + " = " + id, null);
}
Sample code - Model

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

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

     return comment;
 }
Sample code - Model
public 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;
}
No better choice ?
ORM
Object-relational mapping
Record maps to Java Object
Rails sample
We use SQLite @ Android



        OrmLite
        greenDAO
greenDAO
Architecture
Structure
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();
}
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();
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");
}
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");
}
What is generator ?
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
QueryBuilder
●   whereXXX
●   joinXXX
●   orderXXX
●   listXXX
●   uniqueXXX
●   or, and
●   limit, offset, count
FAQ
1. Why use generator ?
Typically, annotation & reflection



            BUT
1.can't compiler check
2.reflection is very slow @ Android
2. Why use greenDAO ?
Speed up !
1.generator instead of reflection
2.refine SQLiteCursor
3.custom LongHashMap @ LUT
3. What about OrmLite ?
References
●   http://greendao-orm.com/
●   https://github.com/greenrobot/greenDAO
●   http://www.slideshare.net/droidcon/green-dao
49

Weitere ähnliche Inhalte

Was ist angesagt?

MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB
 
Fast querying indexing for performance (4)
Fast querying   indexing for performance (4)Fast querying   indexing for performance (4)
Fast querying indexing for performance (4)MongoDB
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query OptimizationMongoDB
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)MongoDB
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaScott Hernandez
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legione-Legion
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidRodrigo de Souza Castro
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query OptimizationMongoDB
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBMongoDB
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationMongoDB
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
Reducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQLReducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQLMongoDB
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDBantoinegirbal
 
MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329Douglas Duncan
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickHermann Hueck
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Scott Leberknight
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Hermann Hueck
 

Was ist angesagt? (20)

MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
 
Fast querying indexing for performance (4)
Fast querying   indexing for performance (4)Fast querying   indexing for performance (4)
Fast querying indexing for performance (4)
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no android
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDB
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
Reducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQLReducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQL
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB
 
MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 

Andere mochten auch

Wei_Zhao_Resume
Wei_Zhao_ResumeWei_Zhao_Resume
Wei_Zhao_ResumeWei Zhao
 
Resume_Yilun Chong_EN
Resume_Yilun Chong_ENResume_Yilun Chong_EN
Resume_Yilun Chong_ENYilun Chong
 
Kafka文件系统设计
Kafka文件系统设计Kafka文件系统设计
Kafka文件系统设计志涛 李
 
Zejia_CV_final
Zejia_CV_finalZejia_CV_final
Zejia_CV_finalZJ Zheng
 
Fast flux domain detection
Fast flux domain detectionFast flux domain detection
Fast flux domain detectionNi Zhiqiang
 
前端规范(初稿)
前端规范(初稿)前端规范(初稿)
前端规范(初稿)EnLei-Cai
 
台湾趴趴走
台湾趴趴走台湾趴趴走
台湾趴趴走Limbo Wong
 
冯宏华:H base在小米的应用与扩展
冯宏华:H base在小米的应用与扩展冯宏华:H base在小米的应用与扩展
冯宏华:H base在小米的应用与扩展hdhappy001
 
Xiaoli_Ma_developer_resume
Xiaoli_Ma_developer_resumeXiaoli_Ma_developer_resume
Xiaoli_Ma_developer_resumeXiaoli Ma
 
Dpdk Validation - Liu, Yong
Dpdk Validation - Liu, YongDpdk Validation - Liu, Yong
Dpdk Validation - Liu, Yongharryvanhaaren
 
CV_Shilidong
CV_ShilidongCV_Shilidong
CV_Shilidong?? ?
 
Cheng_Wang_resume
Cheng_Wang_resumeCheng_Wang_resume
Cheng_Wang_resumeCheng Wang
 

Andere mochten auch (19)

Wei_Zhao_Resume
Wei_Zhao_ResumeWei_Zhao_Resume
Wei_Zhao_Resume
 
Resume_Yilun Chong_EN
Resume_Yilun Chong_ENResume_Yilun Chong_EN
Resume_Yilun Chong_EN
 
Kafka文件系统设计
Kafka文件系统设计Kafka文件系统设计
Kafka文件系统设计
 
Sara Saile cv
Sara Saile cv Sara Saile cv
Sara Saile cv
 
Lichang Wang_CV
Lichang Wang_CVLichang Wang_CV
Lichang Wang_CV
 
Zejia_CV_final
Zejia_CV_finalZejia_CV_final
Zejia_CV_final
 
Fast flux domain detection
Fast flux domain detectionFast flux domain detection
Fast flux domain detection
 
CV-YacineRhalmi
CV-YacineRhalmiCV-YacineRhalmi
CV-YacineRhalmi
 
Cv 12112015
Cv 12112015Cv 12112015
Cv 12112015
 
前端规范(初稿)
前端规范(初稿)前端规范(初稿)
前端规范(初稿)
 
台湾趴趴走
台湾趴趴走台湾趴趴走
台湾趴趴走
 
周士云的简历
周士云的简历周士云的简历
周士云的简历
 
冯宏华:H base在小米的应用与扩展
冯宏华:H base在小米的应用与扩展冯宏华:H base在小米的应用与扩展
冯宏华:H base在小米的应用与扩展
 
Hung DO-DUY - Spikenet
Hung DO-DUY - Spikenet Hung DO-DUY - Spikenet
Hung DO-DUY - Spikenet
 
dpdp
dpdpdpdp
dpdp
 
Xiaoli_Ma_developer_resume
Xiaoli_Ma_developer_resumeXiaoli_Ma_developer_resume
Xiaoli_Ma_developer_resume
 
Dpdk Validation - Liu, Yong
Dpdk Validation - Liu, YongDpdk Validation - Liu, Yong
Dpdk Validation - Liu, Yong
 
CV_Shilidong
CV_ShilidongCV_Shilidong
CV_Shilidong
 
Cheng_Wang_resume
Cheng_Wang_resumeCheng_Wang_resume
Cheng_Wang_resume
 

Ähnlich wie greenDAO

Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)Marius Bugge Monsen
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019corehard_by
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful weddingStéphane Wirtel
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaJevgeni Kabanov
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! aleks-f
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)MongoDB
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Dinesh Neupane
 
Entity Framework Core: tips and tricks
Entity Framework Core: tips and tricksEntity Framework Core: tips and tricks
Entity Framework Core: tips and tricksArturDr
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607Kevin Hazzard
 
DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)cruisercoder
 

Ähnlich wie greenDAO (20)

Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
 
Java and xml
Java and xmlJava and xml
Java and xml
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
 
Entity Framework Core: tips and tricks
Entity Framework Core: tips and tricksEntity Framework Core: tips and tricks
Entity Framework Core: tips and tricks
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)
 
Android examples
Android examplesAndroid examples
Android examples
 

Mehr von Mu Chun Wang

如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進Mu Chun Wang
 
深入淺出 autocomplete
深入淺出 autocomplete深入淺出 autocomplete
深入淺出 autocompleteMu Chun Wang
 
你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事Mu Chun Wang
 
網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體Mu Chun Wang
 
老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統Mu Chun Wang
 
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能Mu Chun Wang
 
Funliday 新創生活甘苦談
Funliday 新創生活甘苦談Funliday 新創生活甘苦談
Funliday 新創生活甘苦談Mu Chun Wang
 
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度Mu Chun Wang
 
如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件Mu Chun Wang
 
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題Mu Chun Wang
 
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構Mu Chun Wang
 
Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?Mu Chun Wang
 
Git 可以做到的事
Git 可以做到的事Git 可以做到的事
Git 可以做到的事Mu Chun Wang
 
那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-Control那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-ControlMu Chun Wang
 
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化Mu Chun Wang
 
如何與全世界分享你的 Library
如何與全世界分享你的 Library如何與全世界分享你的 Library
如何與全世界分享你的 LibraryMu Chun Wang
 
如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌Mu Chun Wang
 
API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一Mu Chun Wang
 
團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作Mu Chun Wang
 

Mehr von Mu Chun Wang (20)

如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進
 
深入淺出 autocomplete
深入淺出 autocomplete深入淺出 autocomplete
深入淺出 autocomplete
 
你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事
 
網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體
 
老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統
 
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
 
Funliday 新創生活甘苦談
Funliday 新創生活甘苦談Funliday 新創生活甘苦談
Funliday 新創生活甘苦談
 
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
 
如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件
 
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
 
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
 
Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?
 
Git 可以做到的事
Git 可以做到的事Git 可以做到的事
Git 可以做到的事
 
那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-Control那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-Control
 
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
 
如何與全世界分享你的 Library
如何與全世界分享你的 Library如何與全世界分享你的 Library
如何與全世界分享你的 Library
 
如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌
 
API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一
 
團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作
 
Git 經驗分享
Git 經驗分享Git 經驗分享
Git 經驗分享
 

Kürzlich hochgeladen

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 

Kürzlich hochgeladen (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

greenDAO

  • 2. Agenda ● SQL syntax ● SQLite @ Android ● ORM ● greenDAO
  • 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. INSERT ● INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob') ● INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
  • 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. DELETE ● DELETE FROM Persons WHERE LastName='Tjessem' AND FirstName='Jakob'
  • 9. 4 components ● SQLiteOpenHelper ● SQLiteDatabase ● SQLiteQueryBuilder ● Cursor
  • 10. SQLiteOpenHelper A helper class to manage database creation and version management.
  • 11. SQLiteDatabase + SQLiteQueryBuilder delete * 1 append * 3 insert * 3 replace(update) * 4 open * 5 query * 15
  • 12. Oh my god, I'm a professional DBA!!!
  • 13. Never mind, we have...... execSQL * 2 db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)");
  • 14. and rawQuery * 4 db.rawQuery("select count(*) from person", null);
  • 16. Cursor getDataType * 16 movePosition * 6 isXXX * 6
  • 17. 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
  • 18. 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
  • 19. Sample code - Controller if (getListAdapter().getCount() > 0) { comment = (Comment) getListAdapter().getItem(0); datasource.deleteComment(comment); adapter.remove(comment); } delete
  • 20. Sample code - Model @Override public void onCreate(SQLiteDatabase database) { database.execSQL("create table " + TABLE_COMMENTS + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_COMMENT + " text not null);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS); onCreate(db); }
  • 21. 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); }
  • 22. Sample code - Model public void deleteComment(Comment comment) { long id = comment.getId(); database.delete("comments", "_id" + " = " + id, null); }
  • 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. Sample code - Model public 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; }
  • 27.
  • 28. Record maps to Java Object
  • 30. We use SQLite @ Android OrmLite greenDAO
  • 34. 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(); }
  • 35. 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();
  • 36. 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"); }
  • 37. 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"); }
  • 39. 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
  • 40. QueryBuilder ● whereXXX ● joinXXX ● orderXXX ● listXXX ● uniqueXXX ● or, and ● limit, offset, count
  • 41. FAQ
  • 42. 1. Why use generator ?
  • 43. Typically, annotation & reflection BUT 1.can't compiler check 2.reflection is very slow @ Android
  • 44. 2. Why use greenDAO ?
  • 45. Speed up ! 1.generator instead of reflection 2.refine SQLiteCursor 3.custom LongHashMap @ LUT
  • 46. 3. What about OrmLite ?
  • 47.
  • 48. References ● http://greendao-orm.com/ ● https://github.com/greenrobot/greenDAO ● http://www.slideshare.net/droidcon/green-dao
  • 49. 49