greenDao3.0 的基本使用
greenDao3.0 的基本使用前言:greenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案。greenDao3.0 相对于2.0版本使用起来更简单易懂,大大降低学习成本。 优势:
集成步骤:gradle配置添加库buildscript {
repositories {
jcenter()
mavenCentral() //<-- add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1' //<-- add plugin
}
}
添加插件apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
配置版本/Dao文件生成路径greendao {
schemaVersion 1000 //版本配置,如果版本升级中有修改表结构,需要修改此版本号
daoPackage 'org.greenrobot.greendao.example.Dao' //生成的DaoMaster,DaoSession,NoteDao的包名,不设置默认为项目包名
targetGenDir 'src/main/java' //生成的DaoMaster,NoteDao的位置,不设置默认为buildgeneratedsourcegreendao
}
Compile配置dependencies {
compile 'org.greenrobot:greendao:3.2.0' //<-- add library
}
greenDao初始化greenDao在使用之间需要对其进行初始化,建议在application中进行实例化并拿到daoSession。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 = true;
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;
}
}
通过application拿到daoSession,然后在Activity和Fragment中获取noteDao注:这里的noteDao是自定义的实体类。后面会有用userDao替代。 // do this in your activities/fragments to get hold of a DAO
noteDao = daoSession.getNoteDao();
使用:新建实体类@Entity
public class User {
@Id
private Long id;
private String name;
@Transient
private int tempUsageCount; // not persisted
@Generated(hash = 873297011)
public User(Long id,String name) {
this.id = id;
this.name = name;
}
}
编译先进行编译,greenDao 3.0会在User中生成对应的set,get方法。同时会在gradle指定的路径和包中生成userDao,DaoMaster,DaoSession。 初始化在前面已经有介绍,这里不做详细解释了。 使用拿到userDao对象,数据库的基本操作通过它来实现。 DaoSession daoSession = ((App) getApplication()).getDaoSession(); userDao = daoSession.getUserDao(); 增User user = new User((long)1,"user1");
userDao.insert(user);
删userDao.deleteByKey(userId); 改User user = new User((long)2,"anye0803");
userDao.update(user);
查如果要排序的话: Query<User> usersQuery;
usersQuery = userDao.queryBuilder().orderAsc(UserDao.Properties.Id).build(); //查询user,根据ID排序
List<User> users = usersQuery.list();
如果不排序的话: List<User> users = userDao.loadAll();
String userName = "";
for (int i = 0; i < users.size(); i++) {
userName += users.get(i).getName()+",";
}
greendao中的注解(没有一一尝试,可以都试试)(一) 定义实体(类名上的注解)@Entity 定义实体 (二) 属性和方法上的注解@Id 总结:greenDao 3.0 暂时写到这,还有一些操作自己慢慢探索中,不知道以后没有机会看看源码再写一篇源码分析。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |