GreenDAO
Code Generation
Code Generation
Generator Project
1. Create java module
2. Add gradle script
3. Create DB Schema
4. Compile and run
Create DB Schema
public static void main(String[] args){
// DB版本號 , 目標 package name
Schema schema = new Schema(1, "com.yanbin.clustering.dao");
createTable(schema);
generateDaoFiles(schema);
}
Create Table
private static void createTable(Schema schema){
//一個Entity 對應一個 DB table
Entity point = schema.addEntity("Point");
//add table column
point.addIdProperty();
point.addDoubleProperty("xPos").notNull();
point.addDoubleProperty("yPos").notNull();
}
Available Types
1. Boolean
2. Byte
3. Short, Long, Int, Float, Double
4. ByteArray
5. String
6. Date
Date Format in GreenDAO
● Not “YYYY-MM-DD HH:MM:SS.SSS”
● Actually It is INTEGER as Unix Time
● Compare greenDAO date with date.
getTime();
Generate DAO Files
private static void generateDaoFiles(Schema schema){
try {
DaoGenerator generator = new DaoGenerator();
//建立到指定目錄
generator.generateAll(schema, "../Clustering/app/src/main/java");
} catch (Exception e){
e.printStackTrace();
}
}
Android Project
Gradle
● build.gradle
dependencies {
...
compile 'de.greenrobot:greendao:1.3.7'
...
}
Core classes
Get DAO Session
private static final String DB_NAME = "clustering.db";
private DaoSession daoSession;
private DBHelper(Context context) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
DaoMaster daoMaster = new DaoMaster(helper.getWritableDatabase());
daoSession = daoMaster.newSession();
}
Insert
public class DBHelper {
public PointDao getNoteDao(){
return daoSession.getPointDao();
}
}
-----------------------------------------------------------------------------------------------------------------------------
PointDao pointDao = DBHelper.getInstance(this).getNoteDao();
...
//run on background thread
pointDao.insert(new Point(null, x, y));
Insert at Background
1. For not block MainThread
2. Data consistency
Insert at Background
1. For not block MainThread
2. Data consistency
Insert at Background
1. For not block MainThread
2. Data consistency
GreenDAO will handle this
https://github.
com/greenrobot/greenDAO/blob/master/DaoCore/src/de/greenrobot/dao/Abstra
ctDao.java
line 258
Insert at Background
1. For not block MainThread
Insert at Background
1. For not block MainThread
AsyncSession
public class DBHelper {
private AsyncSession asyncSession;
...
private DBHelper(Context context) {
...
asyncSession = daoSession.startAsyncSession();
}
...
public AsyncSession getAsyncSession(){
return asyncSession;
}
}
Async Insert
AsyncSession asyncSession = DBHelper.getInstance(this).getAsyncSession();
asyncSession.insert(new Point(null, x, y));
Load By Id, Load All
PointDao pointDao = DBHelper.getInstance(this).getPointDao();
Point point = pointDao.load(pid);
---------------------------------------------------------------------------------------------------
List<Point> points = pointDao.loadAll();
Query
public List<Point> getNegXPoints(){
QueryBuilder<Point> queryBuilder = getPointDao().queryBuilder();
queryBuilder.where(PointDao.Properties.XPos.lt(0))
return queryBuilder.list();
}
Query
public List<Point> getPosXPoints(){
QueryBuilder<Point> queryBuilder = getPointDao().queryBuilder();
queryBuilder.where(PointDao.Properties.XPos.ge(0))
return queryBuilder.list();
}
Query
public List<Point> getNegPoints(){
QueryBuilder<Point> queryBuilder = getPointDao().queryBuilder();
queryBuilder.where(
queryBuilder.and(PointDao.Properties.XPos.lt(0), PointDao.Properties.YPos.lt
(0)))
.orderAsc(PointDao.Properties.XPos);
return queryBuilder.list();
}
QueryBuilder
/**
* Adds the given conditions to the where clause using an logical AND. To create new conditions, use the properties
* given in the generated dao classes.
*/
public QueryBuilder<T> where(WhereCondition cond, WhereCondition... condMore) {
whereCollector.add(cond, condMore);
return this;
}
QueryBuilder
/**
* Adds the given conditions to the where clause using an logical AND. To create new conditions, use the properties
* given in the generated dao classes.
*/
public QueryBuilder<T> where(WhereCondition cond, WhereCondition... condMore) {
whereCollector.add(cond, condMore);
return this;
}
Let’s Look Closer...
WhereCollector
void appendWhereClause(StringBuilder builder, String tablePrefixOrNull, List<Object>
values) {
ListIterator<WhereCondition> iter = whereConditions.listIterator();
while (iter.hasNext()) {
if (iter.hasPrevious()) {
builder.append(" AND ");
}
WhereCondition condition = iter.next();
condition.appendTo(builder, tablePrefixOrNull);
condition.appendValuesTo(values);
}
}
https://github.com/greenrobot/greenDAO/blob/master/DaoCore/src/de/greenrobot/dao/query/WhereCollector.java
WhereCollector
void appendWhereClause(StringBuilder builder, String tablePrefixOrNull, List<Object>
values) {
ListIterator<WhereCondition> iter = whereConditions.listIterator();
while (iter.hasNext()) {
if (iter.hasPrevious()) {
builder.append(" AND ");
}
WhereCondition condition = iter.next();
condition.appendTo(builder, tablePrefixOrNull);
condition.appendValuesTo(values);
}
}
https://github.com/greenrobot/greenDAO/blob/master/DaoCore/src/de/greenrobot/dao/query/WhereCollector.java
Query
public List<Point> getNegPoints(){
QueryBuilder<Point> queryBuilder = getPointDao().queryBuilder();
queryBuilder.where(
queryBuilder.and(PointDao.Properties.XPos.lt(0), PointDao.Properties.YPos.lt
(0)))
.orderAsc(PointDao.Properties.XPos);
return queryBuilder.list();
}
Query
public List<Point> getNegPoints(){
QueryBuilder<Point> queryBuilder = getPointDao().queryBuilder();
queryBuilder.where(PointDao.Properties.XPos.lt(0), PointDao.Properties.YPos.lt(0))
.orderAsc(PointDao.Properties.XPos);
return queryBuilder.list();
}
Query
public List<Point> getNegPoints(){
QueryBuilder<Point> queryBuilder = getPointDao().queryBuilder();
queryBuilder.where(PointDao.Properties.XPos.lt(0), PointDao.Properties.YPos.lt(0))
.orderAsc(PointDao.Properties.XPos);
return queryBuilder.list();
}
List
● List
● LazyList
LazyList
LazyList list = queryBuilder.listLazy();
Item item = list.next();
…
list.close();
LazyList
LazyList list = queryBuilder.listLazy();
Item item = list.next();
…
list.close();
Must be closed
Why?
public class LazyList<E> implements List<E>, Closeable {
private final Cursor cursor;
…
public void close() {
cursor.close();
}
}
Raw query
SQLiteDatabase db = daoSession.getDatabase();
Cursor cursor = db.rawQuery("SELECT SUM(x_pos) FROM point WHERE .....", null);
Others
● Joins
http://greendao-orm.com/documentation/joins/
● Relations
http://greendao-orm.com/documentation/relations/
References
gitbook :
http://bng86.gitbooks.io/android-third-party-/content/greendao.html

Green dao