Greendao的使用
一、引入
(1)工程build.gradle
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| buildscript { repositories { jcenter() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:2.3.2' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' } }
allprojects { repositories { jcenter() } }
task clean(type: Delete) { delete rootProject.buildDir }
|
(2)项目build.gradle
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao' android { greendao { schemaVersion 1; daoPackage'com.mmednet.greendaodemo.greendao' targetGenDir'src/main/java' } } dependencies { compile 'org.greenrobot:greendao:3.2.2 }
|
(3)编写实体类
1 2 3 4 5 6
| @Entity public class StuBean { @Id(autoincrement = true) private Long _id; private String name; private int age;
|
然后Make Project
,然后Greendao就会自动给你生成很多东西.你使用这些就可以进行操作数据库了.
二、注解
- @Entity – 实体注解
- @NotNull – 设置表中当前列的值不可为空
- @Convert – 指定自定义类型(@link PropertyConverter)
- @Generated – GreenDao运行所产生的构造函数或者方法,被此标注的代码可以变更或者下次运行时清除
- @Id – 主键 Long型,可以通过@Id(autoincrement = true)设置自增长。通过这个注解标记的字段必须是Long,数据库中表示它就是主键,并且默认是自增的。
- @Index – 使用@Index作为一个属性来创建一个索引;定义多列索引(@link Entity#indexes())
- @JoinEntity – 定义表连接关系
- @JoinProperty – 定义名称和引用名称属性关系
- @Keep – 注解的代码段在GreenDao下次运行时保持不变
- 注解实体类:默认禁止修改此类
- 注解其他代码段,默认禁止修改注解的代码段
- @OrderBy – 指定排序
- @Property – 设置一个非默认关系映射所对应的列名,默认是的使用字段名 举例:@Property (nameInDb=”name”)
- @ToMany – 定义与多个实体对象的关系
- @ToOne – 定义与另一个实体(一个实体对象)的关系
- @Transient – 添加次标记之后不会生成数据库表的列
- @Unique – 向数据库列添加了一个唯一的约束
方法一览
返回值 |
方法名 |
功能 |
void |
attachEntity(T entity) |
|
long |
count() |
获取数据库中数据的数量 |
// 数据删除相关 |
|
|
void |
delete(T entity) |
从数据库中删除给定的实体 |
void |
deleteAll() |
删除数据库中全部数据 |
void |
deleteByKey(K key) |
从数据库中删除给定Key所对应的实体 |
void |
deleteByKeyInTx(java.lang.Iterable keys) |
使用事务操作删除数据库中给定的所有key所对应的实体 |
void |
deleteByKeyInTx(K… keys) |
使用事务操作删除数据库中给定的所有key所对应的实体 |
void |
deleteInTx(java.lang.Iterable entities) |
使用事务操作删除数据库中给定实体集合中的实体 |
void |
deleteInTx(T… entities) |
使用事务操作删除数据库中给定的实体 |
// 数据插入相关 |
|
|
long |
insert(T entity) |
将给定的实体插入数据库 |
void |
insertInTx(java.lang.Iterable entities) |
使用事务操作,将给定的实体集合插入数据库 |
void |
insertInTx(java.lang.Iterable entities, boolean setPrimaryKey) |
使用事务操作,将给定的实体集合插入数据库, 并设置是否设定主键 |
void |
insertInTx(T… entities) |
将给定的实体插入数据库 |
long |
insertOrReplace(T entity) |
将给定的实体插入数据库,若此实体类存在,则覆盖 |
void |
insertOrReplaceInTx(java.lang.Iterable entities) |
使用事务操作,将给定的实体插入数据库,若此实体类存在,则覆盖 |
void |
insertOrReplaceInTx(java.lang.Iterable entities, boolean |
setPrimaryKey):使用事务操作,将给定的实体插入数据库,若此实体类存在,则覆盖 .并设置是否设定主键 |
void |
insertOrReplaceInTx(T… entities) |
使用事务操作,将给定的实体插入数据库,若此实体类存在,则覆盖 |
long |
insertWithoutSettingPk(T entity) |
将给定的实体插入数据库,但不设定主键 |
// 新增数据插入相关API |
|
|
void |
save(T entity) |
将给定的实体插入数据库,若此实体类存在,则更新 |
void |
saveInTx(java.lang.Iterable entities) |
将给定的实体插入数据库,若此实体类存在,则更新 |
void |
saveInTx(T… entities) |
使用事务操作,将给定的实体插入数据库,若此实体类存在,则更新 |
// 加载相关 |
|
|
T |
load(K key) |
加载给定主键的实体 |
java.util.List |
loadAll() |
加载数据库中所有的实体 |
protected java.util.List |
loadAllAndCloseCursor(android.database.Cursor cursor) |
从cursor中读取、返回实体的列表,并关闭该cursor |
protected java.util.List |
loadAllFromCursor(android.database.Cursor cursor) |
从cursor中读取、返回实体的列表 |
T |
loadByRowId(long rowId) |
加载某一行并返回该行的实体 |
protected T |
loadUnique(android.database.Cursor cursor) |
从cursor中读取、返回唯一实体 |
protected T |
loadUniqueAndCloseCursor(android.database.Cursor cursor) |
从cursor中读取、返回唯一实体,并关闭该cursor |
//更新数据 |
|
|
void |
update(T entity) |
更新给定的实体 |
protected void |
updateInsideSynchronized(T entity, DatabaseStatement stmt, boolean lock) |
|
protected void |
updateInsideSynchronized(T entity, android.database.sqlite.SQLiteStatement stmt, boolean lock) |
|
void |
updateInTx(java.lang.Iterable entities) |
使用事务操作,更新给定的实体 |
void |
updateInTx(T… entities) |
使用事务操作,更新给定的实体 |
查询
1 2 3 4 5 6 7 8 9 10 11 12
| List joes = userDao.queryBuilder() .where(Properties.FirstName.eq("Joe")) .orderAsc(Properties.LastName) .list(); QueryBuilder qb = userDao.queryBuilder();
qb.where(Properties.FirstName.eq("Joe"), qb.or(Properties.YearOfBirth.gt(1970), qb.and(Properties.YearOfBirth.eq(1970), Properties.MonthOfBirth.ge(10)))); List youngJoes = qb.list();
|
limit(int):限制查询返回结果的数目
offset(int):设置查询结果的偏移量,此查询需与limit(int)结合使用,而不能够脱离limit(int)单独使用
指定数据库文件生成目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public class GreenDaoContext extends ContextWrapper { private String currentUserId = "greendao"; private Context mContext;
public GreenDaoContext(Context base) { super(base); mContext = base; }
@Override public File getDatabasePath(String dbName) { String dbDir = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Greendao"; if (TextUtils.isEmpty(dbDir)){ Log.e("SD卡管理:", "SD卡不存在,请加载SD卡"); return null; } File baseFile = new File(dbDir); if (!baseFile.exists()){ baseFile.mkdirs(); } StringBuffer buffer = new StringBuffer(); buffer.append(baseFile.getPath()); buffer.append(File.separator); buffer.append(currentUserId); dbDir = buffer.toString(); buffer.append(File.separator);
buffer.append(dbName); String dbPath = buffer.toString(); File dirFile = new File(dbDir); if (!dirFile.exists()){ dirFile.mkdirs(); } boolean isFileCreateSuccess = false; File dbFile = new File(dbPath); if (!dbFile.exists()) { try { isFileCreateSuccess = dbFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } else isFileCreateSuccess = true; if (isFileCreateSuccess) return dbFile; else return super.getDatabasePath(dbName); }
@Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory); return result; } }
|
使用new DaoMaster.DevOpenHelper(new GreenDaoContext(this), mDbName);