返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Android开发

Android ORM Framework: Getting Started with GreenDao

Introduction to GreenDao GreenDAO is an open-source, lightweight, and fast ORM framework for Android that maps Java objects to SQLite databases. When operating the database, we no longer need to write complex SQL statements. In terms of performance, GreenDAO is highly optimized for Android, with minimal memory overhead, a small dependency size, and it also supports database encryption. GreenDAO official website: http://greenrobot

曦远 (DealiAxy)约 22 分钟
目录30 个章节

Introduction to GreenDao

GreenDAO is an open-source, lightweight, and fast ORM framework for Android that maps Java objects to SQLite databases. When operating the database, we no longer need to write complex SQL statements. In terms of performance, GreenDAO is highly optimized for Android, with minimal memory overhead, a small dependency size, and it also supports database encryption.

GreenDAO official website: http://greenrobot.org/greendao/

GreenDao Features

1. Object Mapping (ORM)

GreenDAO is an ORM framework that can very conveniently map Java objects to an SQLite database for storage.

2. High Performance

There are many ORM frameworks; the more well-known ones include OrmLite, ActiveAndroid, Realm, etc., and their performance varies. The figure below is the performance comparison provided officially by GreenDao.

3. Encryption Support

GreenDao supports encryption and can securely store user data.

4. Lightweight

The GreenDao core library is less than 100k, so we don't need to worry about whether the APK size will become huge after adding GreenDao.

5. Protocol Buffer (protobuf) Protocol Support

GreenDao supports direct storage of protocol buffer (protobuf) protocol data. If you interact with the server via the protobuf protocol, no mapping is needed.

6. Code Generation

greenDAO automatically generates core management classes and DAO objects based on configuration information

7. Open Source

greenDAO is open source. We can download the source code on github to learn. github address: https://github.com/greenrobot/greenDAO

Introduction to Core Classes

DaoMaster:

The entry point for using greenDAO. DaoMaster is responsible for managing database objects (SQLiteDatabase) and DAO classes (objects). We can create SQLite databases of different schemas through its inner classes OpenHelper and DevOpenHelper SQLiteOpenHelper.

DaoSession:

Manages all DAO objects under a specified schema. DaoSession provides some common persistence methods such as insert, load, update, update, and delete entities.

XxxDAO:

For each entity class, greenDAO will generate a corresponding DAO object. For example: for a User entity, a UserDao class will be generated.

Entities

Persistable objects. Typically, entity objects represent a database row using standard Java properties (such as a POJO or JavaBean).

Relationships Between Core Classes

Integrating GreenDAO

Set Up Repository and Plugin (Project: build.gradle)

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

Configure Dependencies (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'//加密库依赖(可选项)
}
greendao {
    schemaVersion 1 //数据库版本号
    daoPackage 'com.speedystone.greendaodemo.db'// 设置DaoMaster、DaoSession、Dao 包名
    targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
}

Quick Start

Let's write a simple entity class (User) and test it

package com.speedystone.greendaodemo.model;

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

/**
 * Created by Speedy on 2017/6/30.
 */
@Entity
public class User {

    @Id
    private long id;

    private String name;

    private int age;

    //此处省略了getter,setter 方法
}

Click Make Project (or Make Moudle ‘App’) to compile the project. If the configuration is correct, DaoMaster, DaoSession, and UserDao classes will be automatically generated under the configured package directory.

Initialize GreenDao (initialization code is usually written in our Application class)

Get UserDao

 MyApp myApp = (MyApp) getApplication();
 DaoSession daoSession =  myApp.getDaoSession();
 UserDao userDao = daoSession.getUserDao();

Save Records

User user = new User();
user.setUserId(1);
user.setName("小明");
user.setAge(16);

userDao.insert(user);
 User user = new User();
 user.setUserId(1);
 user.setName("小明");
 user.setAge(16);

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

Delete Records

public void delete(User user){
    userDao.delete(user);
}

public void deleteByUserId(long userid){
     userDao.deleteByKey(1L);
}

Update Records

public void update(User user){
    userDao.update(user);
}

Query Records

public List<User> query(){
    return userDao.loadAll();// 查询所有记录
}

public User query2(){
        return userDao.loadByRowId(1);//根据ID查询
}

public List<User> query2(){
        return userDao.queryRaw("where AGE>?","10");//查询年龄大于10的用户
}

//查询年龄大于10的用户
public List<User> query4(){
    QueryBuilder<User> builder = userDao.queryBuilder();
    return  builder.where(UserDao.Properties.Age.gt(10)).build().list();
}

Annotation Details

@Entity

Indicates that this entity class will generate a corresponding table in the database

Properties:

  • schema: tells GreenDao which schema the current entity belongs to
  • schema active: marks an entity as being in an active state; active entities have update, delete, and refresh methods
  • nameInDb: the alias used in the database; by default the entity's class name is used,
  • indexes: define indexes, which can span multiple columns
  • createInDb: marks whether to create the database table (default: true)
  • generateConstructors automatically creates a full-parameter constructor (a no-arg constructor will also be generated) (default: true)
  • generateGettersSetters automatically generates getters and setters methods (default: 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

Corresponds to the Id field in the data table

@Index

Use @Index as an attribute to create an index; by default the field name is used

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

    @Index(unique = true)
    private String name;
}

@Property

Sets the column name corresponding to a non-default relationship mapping. By default the field name is used, for example: @Property(nameInDb = “userName”)

@NotNull

Sets the current column of the database table to not be null

@Transient

After adding this annotation, a column will not be generated in the database table

@Unique

Indicates that this property can only have a unique value in the database

@Entity
public class User {
    @Id 
    private Long id;
    @Unique
    private String name;
}

@OrderBy

Sort by a certain field, for example: @OrderBy(“date ASC”)

@ToOne

Represents a one-to-one relationship

@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;
}

@ToMany

Defines a one-to-many relationship with entity objects

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

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

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

References

_EOF_

Android ORM Framework: Getting Started with GreenDao

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

该死的应用闪退,终于解决error-while-inflating-CardView

前言 (先来一个微笑脸)这个问题已经困扰我好久了,之前各种搜索无果,得到的解决方案无非就是 AppCompact 和 CardView 包的版本不一样云云,然而我根本没有这个问题。(怕是不把我Gradle看在眼里?) 问题 就是这么个界面,用到了RecycleView和Cardview,但是在SDK 23以下都不行,官方已经写明这个组件是支持到SDK9还是10的,反正基本是个android手机就可

2022-08-22 · Android开发 · 约 1 分钟

Android开发:对Gradle的折腾记录

前言 有点烦,最近给电脑升级一下配置,加了内存和固态硬盘,结果新内存不太兼容,导致电脑频繁死机,去找商家换了一条内存之后就好了,这也导致我贸然重装了系统 = =... 有一点资料放在系统盘忘记保存结果丢了。今天下午才把新系统配置好,所以这两天都没有办法写推文。 (不得不说Chrome真是好用,这同步功能免去了很多麻烦。) 首先喷一下Gradle 缺点:占用资源大,速度又慢,在国内用网络还很差。 今

2022-05-27 · Android开发 · 约 1 分钟

Android开发:在Linux系统上使用ADB连接Android手机

前言 由于 Linux 系统的安全性设置等原因,非 root 用户使用外部设备或者某些硬件接口会受到限制。Google 官方提供的 SDK 并不能直接工作,如找不到设备或者显示一堆问号以及 Permission Denied。 方法 记得以前有看过 Google 官方提供的解决方案,即将指定的 USB 设备读写权限赋予普通用户。 首先使用 lsusb 命令查看连接到计算机的 usb 设备,找到 A

2021-12-18 · Android开发 · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…