Android--GreenDao

1 简介

greenDAO是一种面向开源的Android的轻便,快捷方式的ORM框架,将Java对象映射到SQLite数据库中,我们操作数据库的时候,不需要编写复杂的SQL语句,在性能方面,greenDAO针对Android进行了高度优化,最小的内存开销,依赖体积小同时还是支持数据库加密。(Github地址

特点:

  • 性能最大化,可能是Android平台上最快的ORM框架
  • 易于使用的API
  • 最小的内存开销
  • 依赖体积小
  • 支持数据库加密
  • 强大的社区支持




2 依赖和混淆规则

依赖:

  • Project: build.gradle:
buildscript {
    
    repositories {
        google()
        jcenter()
        mavenCentral() // add repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.1'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
  • Module:app build.gradle :
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin

dependencies {
    compile 'org.greenrobot:greendao:3.2.2' // add library
    // This is only needed if you want to use encrypted databases
    compile 'net.zetetic:android-database-sqlcipher:3.5.6'//加密库依赖(可选项)
}
  • 配置数据库相关信息 ( Module:app build.gradle )
greendao {
    schemaVersion 1 //数据库版本号
    daoPackage 'com.example.myapplication.db.gen'// 设置DaoMaster、DaoSession、Dao 包名
	targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
}

混淆规则:

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




3 核心类

DaoMaster

使用 greenDAO 的入口点。DaoMaster 负责管理数据库对象(SQLiteDatabase)和 DAO 类(对象),我们可以通过它内部类 OpenHelper 和 DevOpenHelper SQLiteOpenHelper 创建不同模式的 SQLite 数据库。


DaoSession

管理指定模式下的所有 DAO 对象,DaoSession提供了一些通用的持久性方法比如插入、负载、更新、更新和删除实体。


XxxDAO

每个实体类 greenDAO 多会生成一个与之对应DAO对象,如:User 实体,则会生成一个一个UserDao 类


Entities

可持久化对象。通常, 实体对象代表一个数据库行使用标准 Java 属性(如一个POJO 或 JavaBean )。


核心类之间的关系

在这里插入图片描述




4 使用

4.1 写一个实体类

package com.example.myapplication.db;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;

/**
 * @Time: 2020/7/15 0:01
 * @Author: HelloSim
 * @Description :
 */
@Entity
public class User {

    @Id
    private long id;

    private String name;

    private int age;
    
}

4.2 编译工程

点击 Make Project(Make Moudle ‘App’)编译一下工程 。如果配置正确,会在配置的包目录下自动会生成 DaoMaster,DaoSession 和 UserDao 类 。在实体类会生成get/set方法,构造方法。

package com.example.myapplication.db;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;

/**
 * @Time: 2020/7/15 0:01
 * @Author: HelloSim
 * @Description :
 */
@Entity
public class User {

    @Id
    private long id;

    private String name;

    private int age;
    
    @Generated(hash = 446251977)
    public User(long id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Generated(hash = 586692638)
    public User() {
    }

    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }


}

在这里插入图片描述

4.3 初始化 GreenDao ( 通常在 Application 类)

package com.example.myapplication;

import android.database.sqlite.SQLiteDatabase;

import com.example.myapplication.db.gen.DaoMaster;
import com.example.myapplication.db.gen.DaoSession;

/**
 * @Time: 2020/7/15 0:02
 * @Author: HelloSim
 * @Description :
 */
public class Application extends android.app.Application {

    private static DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        initGreenDao();
    }

    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "test.db");
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoSession() {
        return daoSession;
    }

}

4.4 数据库操作

  • 获取 UserDao
DaoSession daoSession = Application.getDaoSession();
UserDao userDao = daoSession.getUserDao();
  • 数据库操作
User user = new User(1, "name", 11);

//保存记录
userDao.insert(user);

//插入或者替换
userDao.insertOrReplace(user);


//删除记录
userDao.delete(user);

//根据id删除记录
userDao.deleteByKey(1L);


//更新记录
user.setAge(12);
userDao.update(user);


//查询所有记录
userDao.loadAll();
//根据ID查询
userDao.loadByRowId(1);
//查询年龄大于10的用户
userDao.queryRaw("where AGE>?", "10");
//查询年龄大于10的用户
userDao.queryBuilder().where(UserDao.Properties.Age.gt(10)).build().list();




5 注解

  • @Entity
    表明这个实体类会在数据库中生成一个与之相对应的表

属性:
schema: 告知GreenDao当前实体属于哪个 schema
schema active: 标记一个实体处于活跃状态,活动实体有更新、删除和刷新方法
nameInDb: 在数据库中使用的别名,默认使用的是实体的类名,
indexes: 定义索引,可以跨越多个列
createInDb: 标记创建数据库表(默认:true)
generateConstructors: 自动创建全参构造方法(同时会生成一个无参构造方法)(默认:true)
generateGettersSetters : 自动生成 getters and setters 方法(默认:true)

@Entity(
        schema = "myschema",
        active = true,
        nameInDb = "AWESOME_USERS",
        indexes = {
                @Index(value = "name DESC", unique = true)
        },
        createInDb = true,
        generateConstructors = false,
        generateGettersSetters = true
)
public class User {
  ...
}
  • @Id
    对应数据表中的 Id 字段

  • @Index
    使用@Index作为一个属性来创建一个索引,默认是使用字段名

@Entity
public class User {
    @Id 
    private Long id;

    @Index(unique = true)
    private String name;
}
  • @Property
    设置一个非默认关系映射所对应的列名,默认是使用字段名,例如:@Property(nameInDb = “userName”)

  • @NotNull
    设置数据库表当前列不能为空

  • @Transient
    添加此标记后不会生成数据库表的列

  • @Unique
    表名该属性在数据库中只能有唯一值

@Entity
public class User {
    @Id 
    private Long id;
    @Unique
    private String name;
}
  • @ToOne
    表示一对一关系
@Entity
public class Order {

    @Id private Long id;

    private long customerId;

    @ToOne(joinProperty = "customerId")
    private Customer customer;
}

@Entity
public class Customer {
    @Id 
    private Long id;
}
  • @OrderBy
    更加某一字段排序 ,例如:@OrderBy(“date ASC”)

  • @ToMany
    定义一对多个实体对象的关系

@Entity
public class Customer {
    @Id private Long id;

    @ToMany(referencedJoinProperty = "customerId")
    @OrderBy("date ASC")
    private List orders;
}

@Entity
public class Order {
    @Id private Long id;
    private Date date;
    private long customerId;
}

Android ORM框架:GreenDao使用详解(基础篇)
Android ORM框架:GreenDao使用详解(进阶篇)
Android ORM框架:GreenDao数据库升级

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值