GreenDao
官方网站地址: http://greenrobot.org/greendao/
github地址 : https://github.com/greenrobot/greenDAO
GreenDao 优点:
1 查询效率高
2 内存占用小
3 集成方便
使用方法:
1 引用(一个都不能少)
APP下的build.gradle
第一句一定不能忘!
apply plugin: 'org.greenrobot.greendao'//这句一定不能忘
android {
greendao {
schemaVersion 1
daoPackage 'com.tongyonghangkong.greendao.gen'//修改为gen文件实际位置,详情第二步
targetGenDir 'src/main/java'
}
}
dependencies {
implementation 'org.greenrobot:greendao:3.1.0'
implementation 'org.greenrobot:greendao-generator:3.1.0'
implementation 'com.jakewharton:butterknife:8.1.0'
}
project 下的build.gradle
两句标识 “这一句” 的一定不能忘
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
mavenCentral()//这一句
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven{url "https://jitpack.io"}//这一句
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
2 手动创建greendao.gen文件夹,用来存放被greenDao自动生成的代码
3 初始化greenDao
首先要准备两个类: DaoMaster DaoSession
package com.tongyonghangkong.greendao.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 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
ZhenHangDao.createTable(db, ifNotExists);
WokersDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
ZhenHangDao.dropTable(db, ifExists);
WokersDao.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(ZhenHangDao.class);
registerDaoClass(WokersDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
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. */
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);
}
}
}
package com.tongyonghangkong.greendao.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;
import com.tongyonghangkong.bean.ZhenHang;
import com.tongyonghangkong.bean.Wokers;
import com.tongyonghangkong.greendao.gen.ZhenHangDao;
import com.tongyonghangkong.greendao.gen.WokersDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig zhenHangDaoConfig;
private final DaoConfig wokersDaoConfig;
private final ZhenHangDao zhenHangDao;
private final WokersDao wokersDao;
public DaoSession(Database db, IdentityScopeType type, Map>, DaoConfig>
daoConfigMap) {
super(db);
zhenHangDaoConfig = daoConfigMap.get(ZhenHangDao.class).clone();
zhenHangDaoConfig.initIdentityScope(type);
wokersDaoConfig = daoConfigMap.get(WokersDao.class).clone();
wokersDaoConfig.initIdentityScope(type);
zhenHangDao = new ZhenHangDao(zhenHangDaoConfig, this);
wokersDao = new WokersDao(wokersDaoConfig, this);
registerDao(ZhenHang.class, zhenHangDao);
registerDao(Wokers.class, wokersDao);
}
public void clear() {
zhenHangDaoConfig.getIdentityScope().clear();
wokersDaoConfig.getIdentityScope().clear();
}
public ZhenHangDao getZhenHangDao() {
return zhenHangDao;
}
public WokersDao getWokersDao() {
return wokersDao;
}
}
复制到greenDao.gen的类之后,在APPlication中进行初始化greenDao: 调用setDatabase()方法
private void setDatabase() {
mHelper = new DaoMaster.DevOpenHelper(this, "notes_db", null);
db = mHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public SQLiteDatabase getDb() {
return db;
}
4 开始创建你的表
package com.tongyonghangkong.bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
/**
* Created by Administrator on 2019/3/12.
*/
@Entity
public class Wokers {
@Id
public Long id;
public String name;
public String age;
public String sex;
}
创建bean类,具体格式如上
点击build的Make project 之后,自动生成的文件:
package com.tongyonghangkong.greendao.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;
import com.tongyonghangkong.bean.ZhenHang;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "ZHEN_HANG".
*/
public class ZhenHangDao extends AbstractDao {
public static final String TABLENAME = "ZHEN_HANG";
/**
* Properties of entity ZhenHang.
* 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 Name = new Property(1, String.class, "name", false, "NAME");
public final static Property Age = new Property(2, int.class, "age", false, "AGE");
public final static Property Sex = new Property(3, String.class, "sex", false, "SEX");
};
public ZhenHangDao(DaoConfig config) {
super(config);
}
public ZhenHangDao(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 + "\"ZHEN_HANG\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"NAME\" TEXT NOT NULL ," + // 1: name
"\"AGE\" INTEGER NOT NULL ," + // 2: age
"\"SEX\" TEXT);"); // 3: sex
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"ZHEN_HANG\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, ZhenHang entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindString(2, entity.getName());
stmt.bindLong(3, entity.getAge());
String sex = entity.getSex();
if (sex != null) {
stmt.bindString(4, sex);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, ZhenHang entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindString(2, entity.getName());
stmt.bindLong(3, entity.getAge());
String sex = entity.getSex();
if (sex != null) {
stmt.bindString(4, sex);
}
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public ZhenHang readEntity(Cursor cursor, int offset) {
ZhenHang entity = new ZhenHang( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.getString(offset + 1), // name
cursor.getInt(offset + 2), // age
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3) // sex
);
return entity;
}
@Override
public void readEntity(Cursor cursor, ZhenHang entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setName(cursor.getString(offset + 1));
entity.setAge(cursor.getInt(offset + 2));
entity.setSex(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
}
@Override
protected final Long updateKeyAfterInsert(ZhenHang entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(ZhenHang entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
protected boolean hasKey(ZhenHang entity) {
return false;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
插入数据举例:
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.insert(user);
删除数据举例:
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.delete(user);
更新数据举例:
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.update(user);
查找数据举例:
public List queryUserList() {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
QueryBuilder qb = userDao.queryBuilder();
List list = qb.list();
return list;
}
出错解决:
1 android.database.sqlite.SQLiteException: no such table: TASK_SCAN (code 1): , while compiling: SELECT T."_id",T."TASKID",T."TASKCARDID",T."TASKSTATUS" FROM "TASK_SCAN" ……………………
使用greenDao过程中,新建了一个数据类Person并标注@Entity,然后框架自动生成了PersonDao,我使用这个Dao类来对Person表进行操作,然后安装到手机上后报了这个错。
报错信息说没有这个表,这让我非常郁闷,难道每次应用启动的时候框架不会自动检查所有数据表,把新建的数据类映射到数据库中吗?实践证明是不会的,只有应用第一次安装的时候才会在数据库中新建这些表,开发中删除当前的apk重新运行安装一个就可以。
解决方法也很明显了,删掉手机上原有APK再安装即可。
转载自:http://blog.csdn.net/zhang___yong/article/details/77948150