GreenOrm簡介
greenDAO是一個開源的Android ORM使得SQLite數據庫開發又有趣。它使開發人員從數據庫處理低級需求而節省開發時間。SQLite是一個很棒的嵌入式關係數據庫。不過,編寫SQL和解析查詢結果相當繁瑣和耗時的任務。greenDAO釋放你從這些通過將Java對象映射到數據庫表(稱爲ORM對象/關係映射)。這樣你可以存儲、更新、刪除和查詢的Java對象使用一個簡單的面向對象的API。
如果有興趣可以直接訪問 greenDao 官網
greenDao 官方github地址: greenDao官方github地址
greenDao orm 基本使用
添加build依賴
project build.gradle中加入
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
}
}
module build.gradle中加入
apply plugin: 'org.greenrobot.greendao'
dependencies {
compile 'org.greenrobot:greendao:3.2.0'
}
創建對象
@Entity(indexes = {
@Index(value = "text, date DESC", unique = true)
})
public class Note {
@Id
private Long id;//notes: id 需要是Long 類型
@NotNull
private String text;
private Date date;
}
創建好了對象,這時候需要build一下,greendao 會幫助補全 daoSession (操作curd) etc.
application配置
public class App extends Application {
/** A flag to show how easily you can switch from standard SQLite to the encrypted SQLCipher. */
public static final boolean ENCRYPTED = false;
private DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "notes-db-encrypted" : "notes-db");
Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
}
不要忘記在menifest.xml 中註冊application
.實戰
- 獲取daosession對象
DaoSession daoSession = ((App) getApplicationContext()).getDaoSession();
- 增
NoteDao noteDao = daoSession.getNoteDao();
Note note = new Note(null, noteText, comment, new Date(), NoteType.TEXT);
noteDao.insert(note);
- 查
Query<Note> notesQuery = noteDao.queryBuilder().orderAsc(NoteDao.Properties.Text).build();
List<Note> list = notesQuery.list();
- 刪
Long noteId = note.getId();
noteDao.deleteByKey(noteId);