GreenDao3.2简单使用

GreenDao的介绍

greenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案,为android移动开发而产生的一个库。关于greenDAO的概念可以看官网greenDAO,Github。

GreenDao优势

  • Maximum performance (probably the fastest ORM for Android); our benchmarks are open sourced too
  • Easy to use powerful APIs covering relations and joins
  • Small library size (<100KB) to keep your build times low and to avoid the 65k method limit
  • Database encryption: greenDAO supports SQLCipher to keep your user’s data safe
  • Strong community: More than 5.000 GitHub stars show there is a strong and active community

GreenDao环境配置

1.首先在Android studio 项目的project的build.grad 文件中添加
// In your root build.gradle file:
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
  }
}
2.在module的build.gradle文件中添加greenDAO的插件,并引入相关类库
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' <-- apply plugin

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
  greendao {
    schemaVersion 1//版本信息
    /**
     * 输出dao的数据库操作实体类文件夹(相对路径 包名+自定义路径名称,包将创建于包名的直接路径下)
     */
    daoPackage 'com.yushu.greendao.model.greendao'
    /**
     * greenDao实体类包文件夹
     */
    targetGenDir 'src/main/java'
    }
} 
dependencies {
  compile 'org.greenrobot:greendao:3.2.0' <-- add library
}
3 .在项目包下创建实体类
@Entity
public class User {
@Id
private Long id;//@Id必须为Long

@Unique
private long identity;//身份唯一

@Property(nameInDb = "NAME")
private String name;//改变列名

@NotNull
private int age;//不能为空

@Transient
private String hobby;//不存储到数据库
}
4.编译项目MakeProject

编译项目后,User实体类会自动编译,生成get、set方法并且会在 daoPackage 'com.yushu.greendao.model.greendao'目录下生成三个文件;

GreenDao3.2简单使用_第1张图片
QQ截图20170318162643.png

GreenDao的使用

//创建dbmanager类初始化数据库
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "user.db", null);  
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());  
DaoSession daoSession = daoMaster.newSession(); 

// 获取userDao 
userDao = daoSession.getUserDao();  
增删改查:
1. 增
User mUser = new User((long) 2, "123412412412", "yuShu", 18);
userDao.insert(mUser);
2. 删
userDao.deleteByKey((long) 2);
// userDao.delete(mUser);
3. 改
 User mUser = new User((long) 2, "123412412412", "yuShu", 25);
 userDao.update(mUser);
4. 查
userDao.loadAll()//查询所有
QueryBuilder qb = userDao.queryBuilder();
qb.where(UserDao.Properties.Age.eq(18)).orderAsc(UserDao.Properties.Age);
List list = qb.list();

代码混淆

-keep class org.greenrobot.greendao.**{*;}
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties

你可能感兴趣的:(GreenDao3.2简单使用)