返回文章列表文章索引阅读全文
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 许可协议。转载请注明出处!

相关文章

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

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

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

讨论

共 0 条

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

加载评论中…