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?

Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
MongoDB
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
MongoDB
 

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_Resume
Wei Zhao
 
Resume_Yilun Chong_EN
Resume_Yilun Chong_ENResume_Yilun Chong_EN
Resume_Yilun Chong_EN
Yilun Chong
 
Zejia_CV_final
Zejia_CV_finalZejia_CV_final
Zejia_CV_final
ZJ Zheng
 
Xiaoli_Ma_developer_resume
Xiaoli_Ma_developer_resumeXiaoli_Ma_developer_resume
Xiaoli_Ma_developer_resume
Xiaoli Ma
 
CV_Shilidong
CV_ShilidongCV_Shilidong
CV_Shilidong
?? ?
 
Cheng_Wang_resume
Cheng_Wang_resumeCheng_Wang_resume
Cheng_Wang_resume
Cheng 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

Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
Kiev ALT.NET
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
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
Jevgeni 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
 

Ä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

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

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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?
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

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