簡介
greenDao是一個將對象映射到SQLite數(shù)據(jù)庫中的輕量且快速的ORM解決方案虾宇。
我認為GreenDao絕對是目前最好用的Android數(shù)據(jù)庫框架,性能很強厚脉,但是我覺得它最大的優(yōu)點是易用攀细。自從用了GreenDao我都不會寫SQL了寂曹,媽媽表示非常擔心我的SQL知識是否會遺忘干凈。
GitHub:https://github.com/greenrobot/greenDAO
官網(wǎng):http://greenrobot.org/greendao/
使用
1衬潦、導包
compile 'org.greenrobot:greendao-generator:3.2.0'
compile 'org.greenrobot:greendao:3.2.0'
2斤蔓、Gradle配置
apply plugin: 'org.greenrobot.greendao'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
}
}
3、數(shù)據(jù)庫配置
greendao {
schemaVersion 1
daoPackage 'com.asksky.greendao'
targetGenDir 'src/main/java'
}
說明:
schemaVersion:指定數(shù)據(jù)庫版本號别渔,每次數(shù)據(jù)庫表改動只需要在此修改一下版本號附迷,GreenDao就會自動進行相應的表升級操作
daoPackage:dao的包名,包名默認是entity所在的包
targetGenDir:生成庫文件的目錄哎媚,默認為build/generated/source/greendao
generateTests:設置為true可以自動生成單元測試
targetGenDirTests:設置單元測試生成的目錄喇伯,默認為src/androidTest/java
以上參數(shù)除schemaVersion都可以使用默認的,無需配置拨与。generateTests默認false
4稻据、實體類和注解
@Entity
public class User {
@Id
private Long id;
private String name;
@Transient
private int tempUsageCount; // not persisted
// getters and setters for id and user ...
}
-
@Entity
注解的Java類回自動轉(zhuǎn)化為一個數(shù)據(jù)庫支持的實體類。同時會在重新編譯后自動生成Get买喧、Set方法捻悯。 - 實體類中的所有字段的類型不能是常用數(shù)據(jù)類型。int -> Integer 淤毛、 long->Long
- 使用
@Transient
可以讓GreenDao忽略某一變量
5今缚、基本使用
/**
* Created by AskSky on 2016/11/22.
* 數(shù)據(jù)庫輔助類
*/
public class DBHelper {
private static final String TAG = DBHelper.class.getSimpleName();
private static DBHelper mInstance;
private DaoMaster.DevOpenHelper mOpenHelper;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
private String password = "AskSky_TanPeiQi_1195211669_JMSQJ";
private static final String DBName = "testDb";
private DBHelper() {
}
public static DBHelper getInstance() {
if (mInstance == null) {
mInstance = new DBHelper();
}
return mInstance;
}
public void init(Context context) {
mOpenHelper = new DaoMaster.DevOpenHelper(context, DBName, null);
mDaoMaster = new DaoMaster(mOpenHelper.getEncryptedWritableDb(Utils.getMd5(password)));
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getSession() {
return mDaoSession;
}
public DaoMaster getMaster() {
return mDaoMaster;
}
}
**說明:
不要忘記在Application中調(diào)用init()方法初始化
mDaoMaster = new DaoMaster(mOpenHelper.getEncryptedWritableDb(Utils.getMd5(password)));
這一行是開啟數(shù)據(jù)庫加密,若要使用數(shù)據(jù)庫加密低淡,需要導入:
compile 'net.zetetic:android-database-sqlcipher:3.5.4@aar'
**
6 姓言、增刪改查
- 增
DBHelper.getInstance().getSession().getUserDao().insert(mUser);
- 刪
//DBHelper.getInstance().getSession().getUserDao().deleteByKey(mUser.getId());
//DBHelper.getInstance().getSession().getUserDao().delete(mUser);
DBHelper.getInstance().getSession().getUserDao().deleteAll();
- 改
DBHelper.getInstance().getSession().update(mUser);
- 查
List<User> users = DBHelper.getInstance().getSession().getUserDao().loadAll();
很明顯,增刪改查簡單的過分
7蔗蹋、其他注解
@Entity
注解的細節(jié)配置:
@Entity(
// If you have more than one schema, you can tell greenDAO
// to which schema an entity belongs (pick any string as a name).
schema = "myschema",
// Flag to make an entity "active": Active entities have update,
// delete, and refresh methods.
active = true,
// Specifies the name of the table in the database.
// By default, the name is based on the entities class name.
nameInDb = "AWESOME_USERS",
// Define indexes spanning multiple columns here.
indexes = {
@Index(value = "name DESC", unique = true)
},
// Flag if the DAO should create the database table (default is true).
// Set this to false, if you have multiple entities mapping to one table,
// or the table creation is done outside of greenDAO.
createInDb = false,
// Whether an all properties constructor should be generated.
// A no-args constructor is always required.
generateConstructors = true,
// Whether getters and setters for properties should be generated if missing.
generateGettersSetters = true
)
public class User {
...
}
- @Entity 定義實體
- @nameInDb 在數(shù)據(jù)庫中的名字何荚,如不寫則為實體中類名
- @indexes 索引
- @createInDb 是否創(chuàng)建表,默認為true,false時不創(chuàng)建
- @schema 指定架構(gòu)名稱為實體
- @active 無論是更新生成都刷新
8猪杭、成員變量參數(shù)配置
@Entity
public class User {
@Id(autoincrement = true)
private Long id;
@Property(nameInDb = "USERNAME")
private String name;
@NotNull
private int repos;
@Transient
private int tempUsageCount;
...
}
- @Id 主鍵 參數(shù)
autoincrement
表示是否自增長 - @Property 列名
nameInDb
制定具體列名 - @NotNull 非空
- @Transient 指定GreenDao忽略此變量
9餐塘、約束
@Entity
public class User {
@Id private Long id;
@Index(unique = true)
private String name;
}
- @Index 創(chuàng)建數(shù)據(jù)庫索引
unique
添加唯一約束,使所有的值都是唯一的
@Entity
public class User {
@Id private Long id;
@Unique private String name;
}
- @Unique 指定序列使用唯一約束 注意,SQLite還隱式地創(chuàng)建一個索引
總結(jié)
GreenDao是目前比較火的數(shù)據(jù)庫管理框架皂吮,經(jīng)過千千萬萬次驗證戒傻,其穩(wěn)定性和性能自不用說税手,而其易用性也確實很強。本文僅介紹了GreenDao的基本用法需纳,其他高級用法可以去官網(wǎng)查看冈止。如根據(jù)時間倒序查詢前50條數(shù)據(jù)可以這樣寫:
List<Message> data = DBHelper.getInstance().getSession().getMessageDao().queryBuilder()
.orderDesc(MessageDao.Properties.Time).limit(50).list();
我在GitHub上放了一個簡單Demo,大家可以參考一下:
https://github.com/AskSky924/GreenDaoDemo
以上內(nèi)容如有錯誤或不足候齿,歡迎指正熙暴。QQ:1195211669