greendao id string可以设置id吗

GreenDao3使用说明
GreenDao 3
一个将对象映射到 SQLite 中的轻量且快速的ORM解决方案
在项目的 build.gradle 添加:
buildscript {
repositories {
mavenCentral()
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
// 使用数据库升级辅助GreenDaoUpgradeHelper时添加
allprojects {
repositories {
maven { url &https://jitpack.io& }
在模组的 build.gradle 中添加:
apply plugin: 'org.greenrobot.greendao'
dependencies {
compile 'org.greenrobot:greendao:3.2.0'
// 数据库时添加
compile 'net.zetetic:android-database-sqlcipher:3.5.1'
// 使用数据库升级辅助GreenDaoUpgradeHelper时添加
compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v1.2.0'
设置 Schema,在模组的 build.gradle 中添加:
schemaVersion:数据库schema版本号,通过*OpenHelpers迁移数据,schema改变值增加。默认为1 daoPackage:生成DAOs、DaoMaster、DaoSession的包名。默认为entities所在包名。 targetGenDir:生成DAOs、DaoMaster、DaoSession的目录。默认为build/generated/source/greendao generateTests: 设置true自动生成单元测试。 targetGenDirTests: 设置生成单元测试目录。默认为src/androidTest/java
greendao {
schemaVersion 1
daoPackage 'com.example.greendaodemo.dao'
targetGenDir 'src/main/java'
### greenDAO 3
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
-keep class **$Properties
# If you do not use SQLCipher:
-dontwarn org.greenrobot.greendao.database.**
# If you do not use Rx:
-dontwarn rx.**
// schema 名,多个 schema 时设置关联实体。插件产生不支持,需使用产生器
// schema = &myschema&,
// 标记一个实体是否处于活动状态,活动实体有 update、delete、refresh 方法。默认为 false
active = false,
// 表名,默认为类名
nameInDb = &AWESOME_USERS&,
// 定义多列索引
indexes = {
@Index(value = &name DESC&, unique = true)
// 标记是否创建表,默认 true。多实体对应一个表或者表已创建,不需要 greenDAO 创建时设置 false
createInDb = true,
// 是否产生所有参数构造器。默认为 true。无参构造器必定产生
generateConstructors = true,
// 如果没有 get/set 方法,是否生成。默认为 true
generateGettersSetters = true
public class User {
// 主键,autoincrement设置自增
@Id(autoincrement = true)
// 唯一,默认索引
private Long userId;
// 列名,默认使用变量名。变化:customName --& CUSTOM_NAME
@Property(nameInDb = &USERNAME&)
// 索引,unique设置唯一,name设置索引别名
@Index(unique = true)
private long fk_dogId;
private String horseN
// 忽略,不持久化,可用关键字transient替代
@Transient
private int tempUsageC
// 对一,实体属性与外联实体中的ID相对应。默认自动自动生成。fk和对象联动,同时改变。对象懒加载
@ToOne(joinProperty = &fk_dogId&)
// 对多,referencedJoinProperty 指定实体中与外联实体属性相对应的外键
@ToMany(referencedJoinProperty = &fk_userId&)
private List
// 对多,@JoinProperty注解:name 实体中的属性;referencedName 外联实体中的属性。
@ToMany(joinProperties = {
@JoinProperty(name = &horseName&, referencedName = &name&)
private List
// 对多,@JoinEntity注解:entity 中间表;sourceProperty 实体属性;targetProperty 外链实体属性
@JoinEntity(
entity = JoinSheepToUser.class,
sourceProperty = &uId&,
targetProperty = &sId&
private List
public class JoinSheepToUser {
private Long uId;
private Long sId;
public class Sheep {
@Generated:greenDao生产代码注解,手动修改报错 @Keep:替换@Generated,greenDao不再生成,也不报错。@Generated(无hash)也有相同的效果 @ToOne:fk 和对象联动,同时改变。对象懒加载,第一次请求后立即获取对象 @ToMany:集合懒加载并缓存,之后获取集合不查找数据库,即集合数据不变。须手动修改集合,或调用reset方法清理集合
// Application 中执行
// DevOpenHelper 每次数据库升级会清空数据,一般用于开发
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, &notes-db&, null);
Database db = helper.getWritableDb();
DaoSession daoSession = new DaoMaster(db).newSession();
// 在使用的地方获取 DAO
NoteDao noteDao = daoSession.getNoteDao();
insert(T entity)
// 插入指定实体
insertInTx(T... entities)
insertInTx(java.lang.Iterable entities)
insertInTx(java.lang.Iterable entities, boolean setPrimaryKey)
insertWithoutSettingPk(T entity)
// 插入指定实体,无主键
insertOrReplace(T entity)
// 插入或替换指定实体
insertOrReplaceInTx(T... entities)
insertOrReplaceInTx(java.lang.Iterable entities)
insertOrReplaceInTx(java.lang.Iterable entities, boolean setPrimaryKey)
save(T entity)
// 依赖指定的主键插入或修改实体
saveInTx(T... entities)
saveInTx(java.lang.Iterable entities)
deleteAll()
// 删除所有
delete(T entity)
// 删除指定的实体
deleteInTx(T... entities)
deleteInTx(java.lang.Iterable entities)
deleteByKey(K key)
// 删除指定主键对应的实体
deleteByKeyInTx(K... keys)
deleteByKeyInTx(java.lang.Iterable keys)
update(T entity)
updateInTx(T... entities)
updateInTx(java.lang.Iterable entities)
refresh(T entity)
// 从数据库获取值刷新本地实体
detach(T entity)
// 从域中分离实体
detachAll()
// 从域中分离所有实体
AbstractDaoSession
getSession()
getDatabase()
java.lang.String
getTablename()
java.lang.String[]
getAllColumns()
java.lang.String[]
getPkColumns()
java.lang.String[]
getNonPkColumns()
getPkProperty()
Property[]
getProperties()
java.util.List
load(K key)
loadByRowId(long rowId)
QueryBuilder 查询
List joes = userDao.queryBuilder()
// 查询 User
.where(Properties.FirstName.eq(&Joe&))
// 首名为 Joe
.orderAsc(Properties.LastName)
// 末名升序排列
// 返回集合
// Joe,&= 1970.10
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();
QueryBuilder
queryBuilder()
// QueryBuilder
QueryBuilder
where(WhereCondition cond, WhereCondition... condMore)
// 条件,AND 连接
QueryBuilder
whereOr(WhereCondition cond1, WhereCondition cond2, WhereCondition... condMore)
// 条件,OR 连接
QueryBuilder
distinct()
// 去重,例如使用联合查询时
QueryBuilder
limit(int limit)
// 限制返回数
QueryBuilder
offset(int offset)
// 偏移结果起始位,配合limit(int)使用
QueryBuilder
orderAsc(Property... properties)
// 排序,升序
QueryBuilder
orderDesc(Property... properties)
// 排序,降序
QueryBuilder
orderCustom(Property property, java.lang.String customOrderForProperty)
// 排序,自定义
QueryBuilder
orderRaw(java.lang.String rawOrder)
// 排序,SQL 语句
QueryBuilder
preferLocalizedStringOrder()
// 本地化字符串排序,用于加密数据库无效
QueryBuilder
stringOrderCollation(java.lang.String stringOrderCollation)
// 自定义字符串排序,默认不区分大小写
WhereCondition
and(WhereCondition cond1, WhereCondition cond2, WhereCondition... condMore)
// 条件,AND 连接
WhereCondition
or(WhereCondition cond1, WhereCondition cond2, WhereCondition... condMore)
// 条件,OR 连接
Query 重复查询
// Joe,1970
Query query = userDao.queryBuilder().where(
Properties.FirstName.eq(&Joe&), Properties.YearOfBirth.eq(1970)
).build();
List joesOf1970 = query.list();
// Maria,1977
query.setParameter(0, &Maria&);
query.setParameter(1, 1977);
List mariasOf1977 = query.list();
// QueryBuilder
CursorQuery
buildCursor()
CountQuery
buildCount()
DeleteQuery
buildDelete()
// 设置查询参数,从 0 开始
setParameter(int index, java.lang.Object parameter)
setParameter(int index, java.lang.Boolean parameter)
setParameter(int index, java.util.Date parameter)
setLimit(int limit)
// 限制返回数
setOffset(int offset)
// 偏移结果起始位,配合limit(int)使用
// Query 绑定线程,执行非本线程的 Query 抛异常,调用获取本线程 Query
forCurrentThread()
// 获取本线程 Query
获取查询结果
// QueryBuilder、Query
// 返回唯一结果或者 null
uniqueOrThrow()
// 返回唯一非空结果,如果 null 则抛异常
java.util.List
// 返回结果集进内存
// 懒加载,须在 try/finally 代码中关闭。
listLazy()
// 第一次使用返回结果集,所有数据使用后会自动关闭
listLazyUncached()
// 返回虚拟结果集,数据库读取不缓存
CloseableListIterator
listIterator()
// 懒加载数据迭代器,不缓存,所有数据使用后会自动关闭
// QueryBuilder、CountQuery
// 获取结果数量
// QueryBuilder.where() 配合 WhereCondition.StringCondition() 实现SQL查询
Query query = userDao.queryBuilder()
.where(new WhereCondition.StringCondition(&_ID IN (SELECT USER_ID FROM USER_MESSAGE WHERE READ_FLAG = 0)&))
// Dao.queryRawCreate() 实现SQL查询
Query query = userDao.queryRawCreate(
&, GROUP G WHERE G.NAME=? AND T.GROUP_ID=G._ID&, &admin&);
java.util.List
queryRaw(java.lang.String where, java.lang.String... selectionArg)
queryRawCreate(java.lang.String where, java.lang.Object... selectionArg)
queryRawCreateListArgs(java.lang.String where, java.util.Collection selectionArg)
// WhereCondition.PropertyCondition
PropertyCondition(Property property, java.lang.String op)
PropertyCondition(Property property, java.lang.String op, java.lang.Object value)
PropertyCondition(Property property, java.lang.String op, java.lang.Object[] values)
// WhereCondition.StringCondition
StringCondition(java.lang.String string)
StringCondition(java.lang.String string, java.lang.Object value)
StringCondition(java.lang.String string, java.lang.Object... values)
DeleteQuery 删除查询
DeleteQuery
buildDelete()
// QueryBuilder
QueryBuilder.LOG_SQL =
QueryBuilder.LOG_VALUES =
DaoSession 增删改查
// DaoSession 的方法转换成 Dao 的对应方法执行
insert(T entity)
insertOrReplace(T entity)
delete(T entity)
deleteAll(java.lang.Class entityClass)
update(T entity)
load(java.lang.Class entityClass, K key)
java.util.List
loadAll(java.lang.Class entityClass)
QueryBuilder
queryBuilder(java.lang.Class entityClass)
java.util.List
queryRaw(java.lang.Class entityClass, java.lang.String where, java.lang.String... selectionArgs)
refresh(T entity)
// 芝麻街住户
QueryBuilder queryBuilder = userDao.queryBuilder();
queryBuilder.join(Address.class, AddressDao.Properties.userId)
.where(AddressDao.Properties.Street.eq(&Sesame Street&));
List users = queryBuilder.list();?
// 欧洲超过百万人口的城市
QueryBuilder qb = cityDao.queryBuilder().where(Properties.Population.ge(1000000));
Join country = qb.join(Properties.CountryId, Country.class);
Join continent = qb.join(country, CountryDao.Properties.ContinentId,
Continent.class, ContinentDao.Properties.Id);
continent.where(ContinentDao.Properties.Name.eq(&Europe&));
List bigEuropeanCities = qb.list();
// 爷爷叫林肯的人
QueryBuilder qb = personDao.queryBuilder();
Join father = qb.join(Person.class, Properties.FatherId);
Join grandfather = qb.join(father, Properties.FatherId, Person.class, Properties.Id);
grandfather.where(Properties.Name.eq(&Lincoln&));
List lincolnDescendants = qb.list();
// QueryBuilder,联合查询
join(java.lang.Class destinationEntityClass, Property destinationProperty)
join(Property sourceProperty, java.lang.Class destinationEntityClass)
join(Property sourceProperty, java.lang.Class destinationEntityClass, Property destinationProperty)
join(Join sourceJoin, Property sourceProperty, java.lang.Class destinationEntityClass, Property destinationProperty)
自定义类型
默认支持类型:byte[]、String、Date、
boolean、int、short、long、float、double、byte、
Boolean、Integer、Short、Long、Float、Double、Byte
// enum 转换为 Integer
public class User {
@Convert(converter = RoleConverter.class, columnType = Integer.class)
public enum Role {
DEFAULT(0), AUTHOR(1), ADMIN(2);
// 使用稳定的 id 来转换,不要使用不稳定的名字和顺序
Role(int id) {
public static class RoleConverter implements PropertyConverter {
public Role convertToEntityProperty(Integer databaseValue) {
if (databaseValue == null) {
for (Role role : Role.values()) {
if (role.id == databaseValue) {
return Role.DEFAULT; // 准备一个默认值,防止数据移除时崩溃
public Integer convertToDatabaseValue(Role entityProperty) {
// 判断返回 null
return entityProperty == null ? null : entityProperty.
使用 DevOpenHelper 每次升级数据库,表会删除重建,推荐开发使用。实际使用中建立类继承 DaoMaster.OpenHelper,实现 onUpgrade()
public class MySQLiteOpenHelper extends DaoMaster.OpenHelper {
public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
public void onUpgrade(Database db, int oldVersion, int newVersion) {
if (oldVersion == newVersion) {
Log.d(&onUpgrade&, &数据库是最新版本& + oldVersion + &,不需要升级&);
Log.d(&onUpgrade&, &数据库从版本& + oldVersion + &升级到版本& + newVersion);
switch (oldVersion) {
String sql = &&;
db.execSQL(sql);
// 初始化使用 MySQLiteOpenHelper
MySQLiteOpenHelper helper = new MySQLiteOpenHelper(this, &notes-db&, null);
Database db = helper.getWritableDb();
DaoSession daoSession = new DaoMaster(db).newSession();
另有升级辅助库 GreenDaoUpgradeHelper,通过 MigrationHelper 在删表重建的过程中,使用临时表保存数据并还原。
注意:MigrationHelper.migrate(),暂时只接收 SQLiteDatabase ,不接收 Database,影响加密的使用。可修改支持。
public class MySQLiteOpenHelper extends DaoMaster.OpenHelper {
public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
MigrationHelper.migrate(db,TestDataDao.class,TestData2Dao.class,TestData3Dao.class);
MigrationHelper.DEBUG = //如果你想查看日志信息,请将DEBUG设置为true
MySQLiteOpenHelper helper = new MySQLiteOpenHelper(this, &test.db&, null);
DaoMaster daoMaster = new DaoMaster(helper.getWritableDatabase());
SQLCipher 加密
使用getEncryptedReadableDb()和getEncryptedWritableDb()获取加密的数据库 256位AES加密,会提升APK的大小 Robolectric 测试时,须使用非加密数据库
DevOpenHelper helper = new DevOpenHelper(this, &notes-db-encrypted.db&);
Database db = helper.getEncryptedWritableDb(&&);
DaoSession daoSession = new DaoMaster(db).newSession();
// DaoSession
RxTransaction
// 返回 IO 线程下的 Observables
RxTransaction
rxTxPlain()
// 返回无线程调度的 Observables
// QueryBuilder关于GreenDao的配置:
在上述配置中的第三步,生成DAO文件时,步骤如下:主菜单-&Run -& Run…
然后就会弹出
选择ExampleDaoGenerator运行就ok了。
注意:可以用“RE文件管理器“来查看数据库,测试是否创建成功。
GreenDao 的基本使用方法
1、如何创建表
在daoexamplegenerator工程下的ExampleDaoGenerator.java文件中添加表,如下:
public class ExampleDaoGenerator {
public static void main(String[] args) throws Exception{
Schema schema = new Schema(1,"com.monlib");
addNote(schema);
addBook(schema);
addStudent(schema);
new DaoGenerator().generateAll(schema,"/Users/baiyuanwei/Documents/androidFiles/CommonLib/app/src/main/java-gen");
* 这是一个note表
private static void addNote(Schema schema){
Entity note = schema.addEntity("Note");
note.addIdProperty();
note.addStringProperty("text").notNull();
note.addDateProperty("date");
note.addStringProperty("comment");
private static void addBook(Schema schema){
Entity book = schema.addEntity("BookLib");
book.addIdProperty();
book.addStringProperty("name");
book.addIntProperty("price");
* 这是一个新建的表
private static void addStudent(Schema schema){
Entity entity = schema.addEntity("Student");
entity.addIdProperty();
entity.addStringProperty("name");
注意:我们在测试的时候,如果修改了此文件,就要重新编译一次此文件,生成DAO文件,最好把测试手机上的此app删掉,重新编译安装,否则就得更改版本号更新。
2、如何使用生成的DAO 文件
我们自定义Application,如下:
public class MyApplication extends Application {
private DaoMaster daoM
private DaoSession daoS
private SQLiteDatabase sqLiteD
public void onCreate() {
super.onCreate();
setupDataBase();
private void setupDataBase() {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, DbConstant.DB_NAME, null);
sqLiteDatabase = helper.getWritableDatabase();
daoMaster = new DaoMaster(sqLiteDatabase);
daoSession = daoMaster.newSession();
public DaoSession getDaoSession() {
return daoS
我们只要用DaoSession这个对象就可以完成数据库的增删改查了。其中主要的就是DaoMaster、DaoSession、SQLiteDatabase,这些在Application中创建好,我们就相当于在整个app中创建了一次这些变量。
然后我们新建一个DbHelper.java类,完成对数据库增删改查的封装,如下:
public class DbHelper {
private NoteDao noteD
private BookLibDao bookLibD
private static DbHelper dbHelperI
private static Context mC
* 单例模式得到DbHelper的对象
public static DbHelper getDbHelperInstance(Context context) {
if (dbHelperInstance == null) {
dbHelperInstance = new DbHelper();
if (mContext == null) {
mContext =
DaoSession daoSession = ((MyApplication) mContext.getApplicationContext()).getDaoSession();
dbHelperInstance.noteDao = daoSession.getNoteDao();
dbHelperInstance.bookLibDao = daoSession.getBookLibDao();
return dbHelperI
* 如果不存在该书名,就增加数据
public void insertBookLibData(BookLib bookLib) {
if (!isSaveByName(bookLib.getName())){
bookLibDao.insert(bookLib);
* 根据id删除数据
* 也可以根据其它列删除数据
public void deleteBook(int id) {
QueryBuilder&BookLib& qb = bookLibDao.queryBuilder();
DeleteQuery&BookLib& dq = qb.where(BookLibDao.Properties.Id.eq(id)).buildDelete();
dq.executeDeleteWithoutDetachingEntities();
* 删除BookLib表中的所有数据
public void deleteAll() {
bookLibDao.deleteAll();
* 修改数据
* 要知道该条目的主键的值
public void updateBook(BookLib bookLib) {
bookLibDao.update(bookLib);
* 查询booklib表中的所有数据
public List&BookLib& queryAllBookLib() {
return bookLibDao.loadAll();
* 根据name这一列,查询是否已经存在此name
* 也可以根据其它列来查询,只要修改where中的代码就ok了
public boolean isSaveByName(String name) {
QueryBuilder&BookLib& qb = bookLibDao.queryBuilder();
qb.where(BookLibDao.Properties.Name.eq(name));
int count = (int) qb.buildCount().count();
return count & 0 ? true : false;
* 根据书的名字返回书的价格
* -1代表没有此书
public int getPriceByName(String name){
QueryBuilder&BookLib& qb = bookLibDao.queryBuilder();
qb.where(BookLibDao.Properties.Name.eq(name));
if (qb.list().size()&0){
return qb.list().get(0).getPrice();
return -1;
* 根据多个条件来查询
* 返回符合条件的所有booklib
public List&BookLib& getMoreQuery(String name,int price){
QueryBuilder&BookLib& qb = bookLibDao.queryBuilder();
qb.where(BookLibDao.Properties.Name.eq(name),BookLibDao.Properties.Price.eq(price));
return qb.list();
增删改查中,这里只看一下“改“,其它的可以看下代码就应该懂了。在“改“的时候,需要注意:
public void updateBook(BookLib bookLib) {
bookLibDao.update(bookLib);
在bookLib这个变量中,每个属性的值都要有,只是修改需要改的属性,其中主键的值肯定是不能变的,在GreenDao中默认主键是id(暂时不知道怎么设置主键)。
本文已收录于以下专栏:
相关文章推荐
在AndoridStudio中引入GreenDAOGreenDAO整个运行的逻辑是通过配置其提供的JavaSE代码,自动在一个文件夹下生成需要Bean、DAO、DaoMaster、DaoSession...
GreenDao官网地址:http://greenrobot.org/greendao/
greenDAO 是一个将对象映射到 SQLite 数据库中的轻量且快速的 ORM 解决方案。
程序员升职加薪指南!还缺一个“证”!
CSDN出品策划程序员9月规划,专为码农的升职加薪保驾护航,程序员的捷径,你get到了吗?听说阅读了这篇文章的人,都已实现了小梦想~快来揭秘!
我们在使用数据库的时候,大多数都会是多表联合操作,不会只有一个表的,下面我们就来说一下,多表的操作,这里先拿1:n来说。这是我们平时在设计数据库时最常用的模式。下面我来看一下,GreenDao对1:n...
1.实体类的注解:
在Java代码中使用实体类代表我们需要持久化的数据。3.0以后由我们编写实体类,并添加注解。
1)@Entity
该实例是类的注解,告诉greenDAO这个类是需要持久化的实...
GreenDao官方教程
GreenDao使用详解
在Android实际开发中,当要存储一些数据时,大家首先会想到的是什么存储形式?有人说数据库有人说文件。当然两种方式都行。今天就给大家介绍介绍第三方框架GreenDao的使用。好费话不多说,正式开始介...
在注解横行的时代,GreenDao 需要通过新建GreenDaoGenerator工程生成Java数据对象(实体)和DAO对象,已经追赶不上时代前行的步伐了。GreenDao 3.X的注解开发模式,终...
一、相关文档:1 、主页:http://greenrobot.org/greendao/
2、API:http://greenrobot.org/files/greendao/javadoc/cur...
最近需要开始一个新的项目了,考虑到既然是新项目了,那么一些常用的框架肯定也要用当下最火的!这次的新项目中涉及到了本地数据存储,很早前有个项目的本地数据库框架用的是ActiveAndroid,githu...
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)Add greenDAO to your project&模块是针对Android Studio开发者的引用库添加说明,在app和project build.gradle文件中分别编写以下代码并进行同步(Studio界面上有一个同步按钮,不会的自己查)就可以使用greenDao提供的方法来操作SQLite数据库了:
1 buildscript {
repositories {
mavenCentral()
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
9 //上面是在project的build.gradle文件中,下面是在app的build.gradle文件中,具体见后面实例
10 apply plugin: 'org.greenrobot.greendao'
12 dependencies {
compile 'org.greenrobot:greendao:3.1.0'
1 // Top-level build file where you can add configuration options common to all sub-projects/modules.
3 buildscript {
repositories {
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.1'
//greendao
// NOTE: Do not place your applicati they belong
// in the individual module build.gradle files
16 allprojects {
repositories {
22 task clean(type: Delete) {
delete rootProject.buildDir
1 apply plugin: 'com.android.application'
2 apply plugin: 'org.greenrobot.greendao'
//greendao
4 android {
compileSdkVersion 24
buildToolsVersion "24.0.0"
//greendao
schemaVersion 1
targetGenDir 'src/main/java'
defaultConfig {
applicationId "com.learn.greendaotest"
minSdkVersion 22
targetSdkVersion 24
versionCode 1
versionName "1.0"
buildTypes {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
27 dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'org.greenrobot:greendao:3.1.1'
//greendao
1 package com.learn.
3 import org.greenrobot.greendao.annotation.E
4 import org.greenrobot.greendao.annotation.Id;
5 import org.greenrobot.greendao.annotation.P
8 public class Student {
@Property(nameInDb = "NAME")
@Property(nameInDb = "AGE")
private int
1 @Generated(hash = )
2 public Student(Long id, String name, int age) {
this.name =
this.age =
7 @Generated(hash = )
8 public Student() {
10 public Long getId() {
return this.
13 public void setId(Long id) {
16 public String getName() {
return this.
19 public void setName(String name) {
this.name =
22 public int getAge() {
return this.
25 public void setAge(int age) {
this.age =
1 public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Name = new Property(1, String.class, "name", false, "NAME");
public final static Property Age = new Property(2, int.class, "age", false, "AGE");
1 /** Creates the underlying database table. */
2 public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"STUDENT\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"NAME\" TEXT," + // 1: name
"\"AGE\" INTEGER NOT NULL );"); // 2: age
10 /** Drops the underlying database table. */
11 public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"STUDENT\"";
db.execSQL(sql);
1 @Override
2 public Student readEntity(Cursor cursor, int offset) {
Student entity = new Student( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
cursor.getInt(offset + 2) // age
11 @Override
12 public void readEntity(Cursor cursor, Student entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setAge(cursor.getInt(offset + 2));
1 public DaoSession(Database db, IdentityScopeType type, Map&Class&? extends AbstractDao&?, ?&&, DaoConfig&
daoConfigMap) {
super(db);
studentDaoConfig = daoConfigMap.get(StudentDao.class).clone();
studentDaoConfig.initIdentityScope(type);
studentDao = new StudentDao(studentDaoConfig, this);
registerDao(Student.class, studentDao);
13 public StudentDao getStudentDao() {
return studentD
onUpgrade(Database db, int oldVersion, int newVersion)。
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
4 public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
20 /** WARNING: Drops all table on Upgrade! Use only during development. */
21 public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
StudentDao.dropTable(db, ifExists);
1 /** Creates underlying database table using DAOs. */
2 public static void createAllTables(Database db, boolean ifNotExists) {
StudentDao.createTable(db, ifNotExists);
1 public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
1 public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
1 protected final Map&Class&? extends AbstractDao&?, ?&&, DaoConfig& daoConfigM
3 public AbstractDaoMaster(Database db, int schemaVersion) {
this.schemaVersion = schemaV
daoConfigMap = new HashMap&Class&? extends AbstractDao&?, ?&&, DaoConfig&();
CursorFactory
1 DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "student.db", null);
1 DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
2 DaoSession daoSession = daoMaster.newSession();
3 StudentDao studentDao = daoSession.getStudentDao();
1 Student studentLl = new Student(null, "Lilei", 21);
2 Student studentHmm = new Student(null, "Hanmeimei", 21);
3 studentDao.insert(studentLl);
4 studentDao.insert(studentHmm);
* Insert an entity into the table associated with a concrete DAO.
* @return row ID of newly inserted entity
6 public long insert(T entity) {
return executeInsert(entity, statements.getInsertStatement(), true);
long resultLl = studentDao.insert(studentLl);
long resultHmm = studentDao.insert(studentHmm);
showLog("row id of insert Lilei: "+resultLl);
showLog("row id of insert Hanmeimei: "+resultHmm);
1 private final String TAG = "STUDENT";
2 private void showLog(Object message) {
Log.i(TAG, ""+message);
private void showToast(Object message) {
Toast.makeText(MainActivity.this, ""+message, Toast.LENGTH_SHORT).show();
1 List&Student& listQuery = studentDao.queryBuilder().where(StudentDao.Properties.Id.between(1, 8)).limit(5).build().list();
2 for (Student student : listQuery) {
showLog("id: "+student.getId());
showLog("name: "+student.getName());
showLog("age: "+student.getAge());
WhereCondition condition)和limit(int limit)这两个方法,其实看代码也能明白大概了。
1 List&Student& listDelete = (List&Student&) studentDao.queryBuilder().where(StudentDao.Properties.Id.le(3)).build().list();
2 for (Student student : listDelete) {
studentDao.delete(student);
1 Student stu = studentDao.queryBuilder()
.where(StudentDao.Properties.Id.ge(4), StudentDao.Properties.Name.like("%mei%")).build().unique();
3 if (stu == null) {
showToast("实体不存在!");
stu.setName("Lilei");
studentDao.update(stu);
onUpgrade(Database db, int oldVersion, int newVersion)已经在类DaoMaster中实现了,接下来需要做的是改变数据库版本与实体类属性。
1 greendao{
//greendao
schemaVersion 2
targetGenDir 'src/main/java'
2 private L
3 @Property(nameInDb = "NAME")
4 private S
5 @Property(nameInDb = "AGE")
6 private int
7 @Property
8 private S
  本文中的测试案例都是很简单的情况,实际开发时需要处理的数据肯定多得多。熟悉了greenDao框架的思想及用法之后,处理一般性的数据集时会简单、高效很多,通过面向对象的思想为实体类生成对应的操作类,结构清晰,易维护。
  最后给出项目下载链接:。
阅读(...) 评论()

我要回帖

更多关于 greendao id 的文章

 

随机推荐