SlideShare a Scribd company logo
GreenDao
綠道
Heaton
Outline
• Why GreenDao
• Feature
• Performance
• How to getting start
• How to use.
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.
It is popular?
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>
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
Benchmark
• https://github.com/daj/android-orm-
benchmark
• Write 10000
• Read 10000
ORM
Object/relation mapping (ORM)
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”
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();
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”}
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
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
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
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();
HOW TO GETTING START
Create module
How to getting start?
First time is terrible
Create a module to gen greendao code
• In module gradle
– Add Gradle script
– compile 'de.greenrobot:greendao-generator:1.3.1
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/");}
Compile and run to Auto gen Core
classes
DaoMaster
DaoSeesion
CommonDataDao
CommonData
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
CommonData content
public Long getDataID() { return DataID; }
public void setDataID(Long DataID) {
this.DataID = DataID; }
……
……
……
Add it and start to use
• In Used Project gradle
– compile 'de.greenrobot:greendao:1.3.7'
HOW TO USE
INSERT , DELETE , UPDATE,
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();
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();
Raw query
SQLiteDatabase db =
daoSession.getDatabase();
Cursor cursor = db.rawQuery("SELECT *FROM
leftpage WHERE .....", null);
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 .
Delete
• Delete sentence
– CommonDataDao.QueryBuilder()
.where(Properties.Provider.eq(facebook))
.buildDelete()
.executeDeleteWithoutDetachingEntities();
• Delete all
– CommonDataDao.deleteAll();
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.
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
Something here
AsyncSession asyncSession =
DBHelper.getInstance(this).getAsyncSession();
asyncSession.insert(
new CommonData(null, …, …));

More Related Content

PDF
Green dao
PDF
Green dao
PDF
greenDAO
PDF
ORMLite Android
PPTX
greenDAO
PPTX
Slick: Bringing Scala’s Powerful Features to Your Database Access
PDF
Indexing and Query Optimizer (Mongo Austin)
PPT
Fast querying indexing for performance (4)
Green dao
Green dao
greenDAO
ORMLite Android
greenDAO
Slick: Bringing Scala’s Powerful Features to Your Database Access
Indexing and Query Optimizer (Mongo Austin)
Fast querying indexing for performance (4)

What's hot (20)

PPTX
Indexing & Query Optimization
PPTX
Cassandra 2.2 & 3.0
PPTX
Indexing and Query Optimization
PDF
MongoDB World 2016: Deciphering .explain() Output
PPTX
Getting started with Elasticsearch and .NET
PDF
An introduction into Spring Data
PPTX
Morphia: Simplifying Persistence for Java and MongoDB
PPTX
Simplifying Persistence for Java and MongoDB with Morphia
PPTX
MongoDB and Indexes - MUG Denver - 20160329
PDF
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
PDF
The Ring programming language version 1.7 book - Part 48 of 196
PDF
Brief introduction of Slick
PPTX
Reducing Development Time with MongoDB vs. SQL
ODP
2011 Mongo FR - Indexing in MongoDB
PPTX
Webinar: Index Tuning and Evaluation
PPTX
ObjectBox - The new Mobile Database
PDF
Data access 2.0? Please welcome: Spring Data!
PPTX
Php forum2015 tomas_final
PDF
Webinar: MongoDB Persistence with Java and Morphia
PDF
Cloudera Impala, updated for v1.0
Indexing & Query Optimization
Cassandra 2.2 & 3.0
Indexing and Query Optimization
MongoDB World 2016: Deciphering .explain() Output
Getting started with Elasticsearch and .NET
An introduction into Spring Data
Morphia: Simplifying Persistence for Java and MongoDB
Simplifying Persistence for Java and MongoDB with Morphia
MongoDB and Indexes - MUG Denver - 20160329
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
The Ring programming language version 1.7 book - Part 48 of 196
Brief introduction of Slick
Reducing Development Time with MongoDB vs. SQL
2011 Mongo FR - Indexing in MongoDB
Webinar: Index Tuning and Evaluation
ObjectBox - The new Mobile Database
Data access 2.0? Please welcome: Spring Data!
Php forum2015 tomas_final
Webinar: MongoDB Persistence with Java and Morphia
Cloudera Impala, updated for v1.0
Ad

Viewers also liked (10)

PDF
Green dao 3.0
PPTX
Camera2 introdction
PPTX
How to create a camera2
PDF
Camera2 API, SHIM, and HAL 3.2 in Android 5.1
PDF
PPTX
Android 5.0 Camera2 APIs
PPTX
Hidden Camera 3 APIs in Android 4.4 (KitKat)
ODP
Android Camera Architecture
PPTX
Camera 2.0 in Android 4.2
PDF
Mvp in practice
Green dao 3.0
Camera2 introdction
How to create a camera2
Camera2 API, SHIM, and HAL 3.2 in Android 5.1
Android 5.0 Camera2 APIs
Hidden Camera 3 APIs in Android 4.4 (KitKat)
Android Camera Architecture
Camera 2.0 in Android 4.2
Mvp in practice
Ad

Similar to GreenDao Introduction (20)

PPTX
The Pushdown of Everything by Stephan Kessler and Santiago Mola
KEY
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
ODP
Beyond PHP - It's not (just) about the code
PDF
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
PDF
JSLT: JSON querying and transformation
PDF
jQuery for beginners
PPTX
SQL Injection Defense in Python
PDF
Data Exploration with Apache Drill: Day 1
PDF
Building node.js applications with Database Jones
PDF
Spring data requery
PDF
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
PDF
Beyond SQL: Speeding up Spark with DataFrames
PDF
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
PDF
managing big data
PPTX
Portfolio Oversight With eazyBI
PPTX
Jdbc Java Programming
PDF
Alternatives of JPA/Hibernate
PPTX
Alasql JavaScript SQL Database Library: User Manual
The Pushdown of Everything by Stephan Kessler and Santiago Mola
NOSQL101, Or: How I Learned To Stop Worrying And Love The Mongo!
Beyond PHP - It's not (just) about the code
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
JSLT: JSON querying and transformation
jQuery for beginners
SQL Injection Defense in Python
Data Exploration with Apache Drill: Day 1
Building node.js applications with Database Jones
Spring data requery
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
Beyond SQL: Speeding up Spark with DataFrames
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
managing big data
Portfolio Oversight With eazyBI
Jdbc Java Programming
Alternatives of JPA/Hibernate
Alasql JavaScript SQL Database Library: User Manual

Recently uploaded (20)

PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Nekopoi APK 2025 free lastest update
PDF
top salesforce developer skills in 2025.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
Introduction to Artificial Intelligence
PDF
AI in Product Development-omnex systems
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
ai tools demonstartion for schools and inter college
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Nekopoi APK 2025 free lastest update
top salesforce developer skills in 2025.pdf
PTS Company Brochure 2025 (1).pdf.......
ManageIQ - Sprint 268 Review - Slide Deck
ISO 45001 Occupational Health and Safety Management System
Introduction to Artificial Intelligence
AI in Product Development-omnex systems
Odoo Companies in India – Driving Business Transformation.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Wondershare Filmora 15 Crack With Activation Key [2025
Which alternative to Crystal Reports is best for small or large businesses.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
ai tools demonstartion for schools and inter college

GreenDao Introduction

  • 2. Outline • Why GreenDao • Feature • Performance • How to getting start • How to use.
  • 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.
  • 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. 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
  • 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. 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. 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. 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. 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. 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. 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. HOW TO GETTING START Create module
  • 17. How to getting start? First time is terrible
  • 18. Create a module to gen greendao code • In module gradle – Add Gradle script – compile 'de.greenrobot:greendao-generator:1.3.1
  • 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. Compile and run to Auto gen Core classes DaoMaster DaoSeesion CommonDataDao CommonData
  • 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. CommonData content public Long getDataID() { return DataID; } public void setDataID(Long DataID) { this.DataID = DataID; } …… …… ……
  • 23. Add it and start to use • In Used Project gradle – compile 'de.greenrobot:greendao:1.3.7'
  • 24. HOW TO USE INSERT , DELETE , UPDATE,
  • 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. 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. Raw query SQLiteDatabase db = daoSession.getDatabase(); Cursor cursor = db.rawQuery("SELECT *FROM leftpage WHERE .....", null);
  • 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. Delete • Delete sentence – CommonDataDao.QueryBuilder() .where(Properties.Provider.eq(facebook)) .buildDelete() .executeDeleteWithoutDetachingEntities(); • Delete all – CommonDataDao.deleteAll();
  • 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.
  • 32. Something here AsyncSession asyncSession = DBHelper.getInstance(this).getAsyncSession(); asyncSession.insert( new CommonData(null, …, …));

Editor's Notes

  • #4: 接下來投影片重點在於兩點 Feature Performance
  • #6: High performance 比起其他 ormlite ,快了四倍 也比cp 快了不少
  • #9: Content provider 也是一種 半成品 orm Sqlite 是一種 關聯式資料結構 OO 式一種開發概念 如何Mapping 簡單來說就是最後你希望你crud輸入和輸出的資料都是物件
  • #11: 拿load all 來比 不太對吧
  • #23: 作掉很多dirty job
  • #24: 前置作業完成
  • #26: Why use helper Master -> session -> commondataDao
  • #27: Lazy list Id scope
  • #29: 1. For not block MainThread 2. Data consistency