GreenDao3.0框架使用详解

时间:2022-07-27 19:48:25

最近将一个使用蓝牙设备测人体温度的穿戴设备项目做完了,有时间来总结下本项目中使用到的一些基础知识。上次写过关于GreenDao3.0框架在使用前的配置问题,可点击查看GreenDao3.0框架使用时IDE的配置问题,下面将详细的讲解下具体的使用过程。

先了解下GreenDao这个框架:

GreenDao3.0框架使用详解

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

greenDAO 官网地址: http://greenrobot.org/greendao/

DaoMaster:

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

DaoSession :

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

XxxDAO :

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

Entities

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

编译后在gen包下会多出三个类,分别是TempDataDao,DaoMaster,DaoSession.

GreenDao3.0框架使用详解GreenDao3.0框架使用详解GreenDao3.0框架使用详解(想插入图片,但是老是插入不成功,这CSDN也是醉了GreenDao3.0框架使用详解

TempData实体类里面是这样的:

GreenDao3.0框架使用详解

/**
* Created by jjg on 2017/3/23.
*/
@Entity
public class TempData {
@Id
private Long id;
private float temp;
private float touchData;
private String time;
@Generated(hash = 2018402591)
public TempData(Long id, float temp, float touchData, String time) {
this.id = id;
this.temp = temp;
this.touchData = touchData;
this.time = time;
}
@Generated(hash = 1851873653)
public TempData() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public float getTemp() {
return this.temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public float getTouchData() {
return this.touchData;
}
public void setTouchData(float touchData) {
this.touchData = touchData;
}
public String getTime() {
return this.time;
}
public void setTime(String time) {
this.time = time;
}
}

可见这个实体类中有四个属性,分别是id,温度值,接触值,和对应的时间。

我这边是蓝牙每隔8秒发送一个数据过来,APP在拿到数据的时候将数据存到数据库中去,具体怎么使用GreenDao存放数据呢?

首先,我们来分析下TempDataDao,DaoMaster,DaoSession是干嘛用的?

先看下DaoMaster类里面的代码:

package com.myself.zhw.gen;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.identityscope.IdentityScopeType;


// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 2): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 2;//框架版本号为2,也就是说我当前的GreenDao版本是3.2.0版本的

/** Creates underlying database table using DAOs. */
/*创建所有的表格用到的方法,因为表格是建在数据库中的,所以提供了两个参数,
第一个参数是数据库,第二个参数是这个表格是否存在,不存在才创建,存在的话就
不用创建,这个方法中只有一句代码,调用了TmepDataDao类中的最原始的sqlite创建表格的
方法去创建表格(最原始的创建数据库的语法这里就不讲了)*/
public static void createAllTables(Database db, boolean ifNotExists) {
TempDataDao.createTable(db, ifNotExists);
}

/** Drops underlying database table using DAOs. */
/*这个方法是删除所有数据表格用的,具体的删除方法也是使用最原始的sqlite数据库
的增删改查语句实现的,这个方法也是在TempDataDao类中*/
public static void dropAllTables(Database db, boolean ifExists) {
TempDataDao.dropTable(db, ifExists);
}

/**
* WARNING: Drops all table on Upgrade! Use only during development.
* Convenience method using a {@link DevOpenHelper}.
*/
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}

public DaoMaster(SQLiteDatabase db) {//构造方法
this(new StandardDatabase(db));
}

public DaoMaster(Database db) {//构造方法
super(db, SCHEMA_VERSION);
registerDaoClass(TempDataDao.class);
}

public DaoSession newSession() {//拿到DaoSession对象
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}

public DaoSession newSession(IdentityScopeType type) {//拿到DaoSession对象
return new DaoSession(db, type, daoConfigMap);
}

/**
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
*/
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}

public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}

@Override
public void onCreate(Database db) {//表格的创建
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}

/** WARNING: Drops all table on Upgrade! Use only during development. */
/**
* DevOpenHelperDaoMaster的内部类,DevOpenHelper类继承OpenHelper类,而OperHelper类又是继承DatabaseOpenHelper
* 类,DatabaseOpenHelper类又继承SQLiteOpenHelper类,在使用最原始的SQL语句创建数据库的时候,就使用到了SQLiteOpenHelper
* 可见,这里也是一样的
*/
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}

public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}

@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {//表格的更新,更新之前先删,再重新创建
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}

}

从代码结构可以看出,DaoMaster的功能还是很强大的,是个对Dao进行管理和创建数据库的类。

再看下DaoSession类

package com.myself.zhw.gen;

import java.util.Map;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;


// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.

/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {

private final DaoConfig tempDataDaoConfig;

private final TempDataDao tempDataDao;

public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);

tempDataDaoConfig = daoConfigMap.get(TempDataDao.class).clone();
tempDataDaoConfig.initIdentityScope(type);

tempDataDao = new TempDataDao(tempDataDaoConfig, this);

registerDao(TempData.class, tempDataDao);
}

public void clear() {
tempDataDaoConfig.clearIdentityScope();
}

public TempDataDao getTempDataDao() {
return tempDataDao;
}

}
再看下TempDataDao类

package com.myself.zhw.gen;

import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "TEMP_DATA".
*/
public class TempDataDao extends AbstractDao<TempData, Long> {

public static final String TABLENAME = "TEMP_DATA";

/**
* Properties of entity TempData.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Temp = new Property(1, float.class, "temp", false, "TEMP");
public final static Property TouchData = new Property(2, float.class, "touchData", false, "TOUCH_DATA");
public final static Property Time = new Property(3, String.class, "time", false, "TIME");
}


public TempDataDao(DaoConfig config) {
super(config);
}

public TempDataDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}

/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"TEMP_DATA\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"TEMP\" REAL NOT NULL ," + // 1: temp
"\"TOUCH_DATA\" REAL NOT NULL ," + // 2: touchData
"\"TIME\" TEXT);"); // 3: time
}

/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"TEMP_DATA\"";
db.execSQL(sql);
}

@Override
protected final void bindValues(DatabaseStatement stmt, TempData entity) {
stmt.clearBindings();

Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindDouble(2, entity.getTemp());
stmt.bindDouble(3, entity.getTouchData());

String time = entity.getTime();
if (time != null) {
stmt.bindString(4, time);
}
}

@Override
protected final void bindValues(SQLiteStatement stmt, TempData entity) {
stmt.clearBindings();

Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindDouble(2, entity.getTemp());
stmt.bindDouble(3, entity.getTouchData());

String time = entity.getTime();
if (time != null) {
stmt.bindString(4, time);
}
}

@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}

@Override
public TempData readEntity(Cursor cursor, int offset) {
TempData entity = new TempData( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.getFloat(offset + 1), // temp
cursor.getFloat(offset + 2), // touchData
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3) // time
);
return entity;
}

@Override
public void readEntity(Cursor cursor, TempData entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setTemp(cursor.getFloat(offset + 1));
entity.setTouchData(cursor.getFloat(offset + 2));
entity.setTime(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
}

@Override
protected final Long updateKeyAfterInsert(TempData entity, long rowId) {
entity.setId(rowId);
return rowId;
}

@Override
public Long getKey(TempData entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}

@Override
public boolean hasKey(TempData entity) {
return entity.getId() != null;
}

@Override
protected final boolean isEntityUpdateable() {
return true;
}

}
现在如何创建数据库?

创建数据库选择在application中完成

public class tempteratureApplication extends Application {
private static Context mcontext;
private static DaoSession mDaoSession;
@Override
public void onCreate() {
super.onCreate();
mcontext = getApplicationContext();
createDataBase();
GreenDaoManager.getInstance();
}

// public static DaoSession getmDaoSession(){
// return mDaoSession;
// }
//DaoMaster的作用在这里体现了
private void createDataBase(){
DaoMaster.DevOpenHelper devOpenHelper=new DaoMaster.DevOpenHelper(tempteratureApplication.getContext(),"TEMP_DATA");
Log.e("生成devOpenHelper",devOpenHelper+"");
SQLiteDatabase db=devOpenHelper.getWritableDatabase();
Log.e("生成数据库",db+"");
DaoMaster daoMaster=new DaoMaster(db);
mDaoSession=daoMaster.newSession();
}

public static Context getContext(){
return mcontext;
}
}

TempDataDao是继承AbstractDao的,在AbstractDao中有一个向数据库插入数据的方法insert()方法,所以要想插入数据,就要先创建TempDataDao对象,这也是TempDataDao的作用,还有删除,查询,修改等等的语句全部要用到TempDataDao,可在AbstractDao类中查询到。

后面还会继续给出Demo,用一个详细的例子来说明一切。