随着移动端的业务量的增大和用户体验的提高,SQLite的需求很明显了,大大小小的项目几乎成了必备,用我们项目经理的话来说:
1、不用管他什么数据,为了体验,先缓存一下!
2、什么?网络不好导致的?看什么,缓存啊!!!
真不知道他是在哪里听到的这个词,唉!
在他看来,缓存是如此简单的一件事情,当然,缓存其实并不难,就是有点麻烦而已!
之前我一直是用Realm,目前Realm被人称为移动端的新一代王者,但是对于知识,哪有嫌多的呢。
一、GreenDao和Realm对比
我在网上找了一张图片,很能说明问题:
在小量数据的查询与删除等操作中,两者的差距基本可以忽略不计,超过同时插入、删除、查询1000条以上的数据分析得出。GreenDao在删除操作中,占明显优势,而Realm在添加与查询方面优于GreenDAO。各有千秋,看自己的选择。
二、GreenDao配置
1、导入相应的包
compile’org.greenrobot:greendao:3.0.1’
compile’org.greenrobot:greendao-generator:3.0.0’
2、配置app的Gradle
apply plugin: ‘org.greenrobot.greendao’
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath ‘org.greenrobot:greendao-gradle-plugin:3.0.0’
}
}
greendao {
schemaVersion 1
daoPackage ‘com.example.anonymous.greendao.gen’
targetGenDir ‘src/main/java’
}
3、配置greenDao
greendao {
schemaVersion 1
daoPackage ‘com.example.anonymous.greendao’
targetGenDir ‘src/main/java’
}
schemaVersion---->指定数据库schema版本号,迁移等操作会用到
daoPackage-------->通过gradle插件生成的数据库相关文件,这里我设置的文件路径是com.example.anonymous.greendao
targetGenDir-------->这就是我们上面说到的自定义生成数据库文件的目录了,可以将生成的文件放到我们的java目录中,而不是build中,这样就不用额外的设置资源目录了
整体配置预览:
apply plugin: ‘com.android.application’
apply plugin: ‘org.greenrobot.greendao’
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath ‘org.greenrobot:greendao-gradle-plugin:3.0.0’
}
}
greendao {
schemaVersion 1
daoPackage ‘com.example.anonymous.greendao’
targetGenDir ‘src/main/java’
}
android {
compileSdkVersion 25
buildToolsVersion “25.0.2”
defaultConfig {
applicationId “com.example.anonymous.realmdemo”
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName “1.0”
testInstrumentationRunner “android.support.test.runner.AndroidJUnitRunner”
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’
}
}
}
dependencies {
compile fileTree(dir: ‘libs’, include: [’*.jar’])
compile ‘com.android.support:appcompat-v7:25.0.1’
compile’org.greenrobot:greendao:3.0.1’
compile’org.greenrobot:greendao-generator:3.0.0’
}
三、编写实体类(对应的是数据库的每张表)
@Entity
public class User {
@Id
private Long id;
private String name;
}
@Entity:将我们的java普通类变为一个能够被greenDAO识别的数据库类型的实体类
@Id:通过这个注解标记的字段必须是Long类型的,这个字段在数据库中表示它就是主键,并且它默认就是自增的
就这么简单含有两个字段的实体类
然后点击这个按钮
builder完之后会有两个地方发生了变化
这是GreenDao自动为你生成的,路径就是你在gradle中配置的路径
现在只有一个User表,如果再添加一个Age实体类,你在点击Make Project按钮,他还会把AgeDao自动生成出来
四、增、删、改、查
在增、删、改、查之前第一步做的就是需要对数据库进行初始化,不可能就这样直接对实体类操作,这样不太现实的,否则为什么GreenDao会自动生成这么多代码呢?
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getContext(), “my-db”, null);
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
my-db是数据库的名字,自己随便写就行。
通过GreenDao生成的代码,我们可以获取到实体类的实例,也就是数据库表的实例,这样我们才能操作数据库
1、增加
User user1 = new User(null,“zhangsan”);
userDao.insert(user1);
2、删除
User findUser = userDao.queryBuilder().where(UserDao.Properties.Name.eq(“zhangsan”)).build().unique();
if(findUser != null){
userDao.deleteByKey(findUser.getId());
}
3、修改
User findUser = userDao.queryBuilder().where(UserDao.Properties.Name.eq(“zhangsan”)).build().unique();
if(findUser != null) {
findUser.setName(“lisi”);
userDao.update(findUser);
Toast.makeText(MyApplication.getContext(), “修改成功”, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MyApplication.getContext(), “用户不存在”, Toast.LENGTH_SHORT).show();
}
把zhangsan改成lisi
4、查询
List userList = userDao.queryBuilder()
.where(UserDao.Properties.Id.notEq(1))
.limit(5)
.build().list();
查询语句是数据库操作最多的,语句也比较复杂,具体的语句请去看官网
简单封装
其实这样写代码,作为程序员并不能满足,最起码的重用还是需要的,所以简单的封装一下吧
我们需要添加几个类来负责代码的重用工作,先看一下整体的工程结构:
1、MyApplication:返回Context对象
2、DaoManager:初始化数据库,获取相应的操作对象
3、EntityManager:对数据库表的初始化,获取实体类的操作对象
public class MyApplication extends Application {
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getContext() {
return mContext;
}
}
/**
greenDao管理类
*/
public class DaoManager {
private static DaoManager mInstance;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
private DaoManager() {
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getContext(), “my-db”, null);
DaoMaster mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
mDaoSession = mDaoMaster.newSession();
}
public DaoMaster getMaster() {
return mDaoMaster;
}
public DaoSession getSession() {
return mDaoSession;
}
public static DaoManager getInstance() {
if (mInstance == null) {
mInstance = new DaoManager();
}
return mInstance;
}
}
public class EntityManager {
private static EntityManager entityManager;
public UserDao userDao;
/**
* 创建User表实例
*
* @return
*/
public UserDao getUserDao(){
userDao = DaoManager.getInstance().getSession().getUserDao();
return userDao;
}
/**
* 创建单例
*
* @return
*/
public static EntityManager getInstance() {
if (entityManager == null) {
entityManager = new EntityManager();
}
return entityManager;
}
}
三个东西一看便知,但是这个东西怎么用呢?
// TODO: 2017/1/1 一句话就把相应的数据库表的实例返回,进行操作
UserDao userDao = EntityManager.getInstance().getUserDao();
User user1 = new User(null,“zhangsan”);
userDao.insert(user1);
DaoManager和EntityManager主要作用是对数据库和表的初始化工作抽出来作为复用,在Activity中使用的时候,我们可以直接操作表,不需要在初始化工作了。原文链接:https://blog.csdn.net/u014752325/article/details/53996232
GreenDao其他使用(如升级、以及一些参数的具体介绍):
学习/参考地址:
http://www.jianshu.com/p/4e6d72e7f57a
http://blog.csdn.net/qq_30379689/article/details/54410838
http://blog.csdn.net/shineflowers/article/details/53405644
前言
在以前选择数据库框架的时候,接触过GreenDAO,但由于那时的GreenDAO配置起来很繁琐,需要自己创建java库,所以就没使用它。
但如今在3.0版本后,GreenDAO大大简化了使用流程,加上其本身存取快、体积小、支持缓存、支持加密等优点,使得它成为了一个更受欢迎的ORM解决方案。
附上一张官方提供的,GreenDAO、OrmLite、ActiveAndroid的对比图
对比图
介绍
下面分为 配置、建库建表、增删改查、加密、升级、混淆 这几个部分来介绍。
dependencies {
//greendao配置
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
}
Module下的build.gradle文件加入
apply plugin: 'org.greenrobot.greendao'
dependencies {
//greenDAO配置
compile 'org.greenrobot:greendao:3.2.0'
}
1.2 设置版本号、生成路径
android {
//greendao配置
greendao {
//数据库版本号,升级时修改
schemaVersion 1
//生成的DAO,DaoMaster和DaoSession的包路径。默认与表实体所在的包路径相同
daoPackage 'com.dev.base.model.db'
//生成源文件的路径。默认源文件目录是在build目录中的(build/generated/source/greendao)
targetGenDir 'src/main/java'
}
}
//DaoMaster为后面创建表实体后自动生成的类。
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "test.db", null);
2.2 创建数据表
GreenDAO通过ORM(Object Relation Mapping 对象关系映射)的方式创建数据表。即创建一个实体类,将该实体结构映射成数据表的结构。
下面演示如何创建一个”电影收藏”数据表。分两步:创建表实体,Make Project生成代码。
2.2.1 创建表实体
@Entity
public class MovieCollect {
@Id
private Long id;
private String movieImage;
private String title;
private int year;
}
注解介绍:(参考自http://www.jianshu.com/p/4e6d72e7f57a)
@Entity
用来声明类实体,表示它将映射为数据表
@Entity()括号内可加入更详细的设置,如:
nameInDb =“TABLE_NAME” ——> 声明该表的表名,默认取类名
createInDb = true ——> 是否创建表,默认为true
generateConstructors = true ——> 是否生成含所有参数的构造函数,默认为true
generateGettersSetters = true ——> 是否生成getter/setter,默认为true
@Id
用来声明某变量为表的主键,类型使用Long
@Id()括号可加入autoincrement = true表明自增长
@Unique
用来声明某变量的值需为唯一值
@NotNull
用来声明某变量的值不能为null
@Property
@Property(nameInDb = “URL”) 用来声明某变量在表中的实际字段名为URL
@Transient
用来声明某变量不被映射到数据表中
@ToOne、@ToMany
用来声明”对一”和“对多”关系,下面举例说明:
学生与学校之间一对多的关系(一个学生对应一个学校,一个学校对应有多个学生)
@Entity
class Student{
//...省略其他变量
private long fk_schoolId;//外键
@ToOne(joinProperty = "fk_schoolId")
private School school;
}
@Entity
class School{
//...省略其他变量
@ToMany(referencedJoinProperty = "fk_schoolId")
private List<Student> students;
}
学生与课程之间“多对多”的关系(一个学生对应有多门课程,一门课程对应有多个学生)
@Entity
class Student{
//...省略其他变量
@ToMany
@JoinEntity(
entity = StudentWithCourse.class,
sourceProperty = "sId",
targetProperty = "cId"
)
private List<Course> courses;
}
@Entity
class Course{
//...省略其他变量
@ToMany
@JoinEntity(
entity = StudentWithCourse.class,
sourceProperty = "cId",
targetProperty = "sId"
)
private List<Course> courses;
}
@Entity
class StudentWithCourse{
@Id
private Long id;
private Long sId;
private Long cId;
}
2.2.2 Make Project
利用上面注解写好表实体后,通过Build—>Make Project重新编译项目, 将会在表实体中自动生成构造方法和getter/setter方法,另外在指定(或默认)的包中生成DaoMaster、DaoSession以及表实体对应的Dao(如MovieCollectDao)。
其中,
DaoMaster:用于创建数据库以及获取DaoSession
DaoSession:用于获取各个表对应的Dao类
各个表对应的Dao:提供了对表进行增删改查的方法
//DaoManager中代码
//获取DaoSession,从而获取各个表的操作DAO类
public DaoSession getDaoSession() {
if (mDaoSession == null) {
initDataBase();
}
return mDaoSession;
}
//初始化数据库及相关类
private void initDataBase(){
setDebugMode(true);//默认开启Log打印
mSQLiteOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getInstance(), DB_NAME, null);//建库
mDaoMaster = new DaoMaster(mSQLiteOpenHelper.getWritableDatabase());
mDaoSession = mDaoMaster.newSession();
mDaoSession.clear();//清空所有数据表的缓存
}
//是否开启Log
public void setDebugMode(boolean flag) {
MigrationHelper.DEBUG = true;//如果查看数据库更新的Log,请设置为true
QueryBuilder.LOG_SQL = flag;
QueryBuilder.LOG_VALUES = flag;
}
通过DaoSeesion获取目标数据表对应的Dao,然后就可开始进行增删改查的操作了。
MovieCollectDao mMovieCollectDao = DaoManager.getInstance().getDaoSession().getMovieCollectDao();
3.1 增
插入单个数据
MovieCollect movieCollect;
mMovieCollectDao.insert(movieCollect);
插入一组数据
List<MovieCollect> listMovieCollect;
mMovieCollectDao.insertInTx(listMovieCollect);
插入或替换数据
//插入的数据如果已经存在表中,则替换掉旧数据(根据主键来检测是否已经存在)
MovieCollect movieCollect;
mMovieCollectDao.insertOrReplace(movieCollect);//单个数据
List<MovieCollect> listMovieCollect;
mMovieCollectDao.insertOrReplace(listMovieCollect);//一组数据
3.2 删
删除单个数据
MovieCollect movieCollect;
mMovieCollectDao.delete(movieCollect);
删除一组数据
List<MovieCollect> listMovieCollect;
mMovieCollectDao.deleteInTx(listMovieCollect);
删除所有数据
mMovieCollectDao.deleteAll();
3.3 改
修改单个数据
MovieCollect movieCollect;
mMovieCollectDao.update(movieCollect);
修改一组数据
List<MovieCollect> listMovieCollect;
mMovieCollectDao.updateInTx(listMovieCollect);
3.4 查
查询全部数据
List<MovieCollect> listMovieCollect = mMovieCollectDao.loadAll();
查询数量
int count = mMovieCollectDao.count();
条件查询
精确查询(where)
//查询电影名为“肖申克的救赎”的电影
MovieCollect movieCollect =
mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Title.eq("肖申克的救赎")).unique();
//查询电影年份为2017的电影
List<MovieCollect> movieCollect =
mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Year.eq(2017)).list();
模糊查询(like)
//查询电影名含有“传奇”的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Title.like("传奇")).list();
//查询电影名以“我的”开头的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Title.like("我的%")).list();
区间查询
//大于
//查询电影年份大于2012年的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Year.gt(2012)).list();
//大于等于
//查询电影年份大于等于2012年的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Year.ge(2012)).list();
//小于
//查询电影年份小于2012年的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Year.lt(2012)).list();
//小于等于
//查询电影年份小于等于2012年的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Year.le(2012)).list();
//介于中间
//查询电影年份在2012-2017之间的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Year.between(2012,2017)).list();
升序降序
//查询电影年份大于2012年的电影,并按年份升序排序
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Year.gt(2012)).orderAsc(MovieCollectDao.Properties.Year).list();
//查询电影年份大于2012年的电影,并按年份降序排序
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().where(MovieCollectDao.Properties.Year.gt(2012)).orderDesc(MovieCollectDao.Properties.Year).list();
and/or
//and
//查询电影年份大于2012年且电影名以“我的”开头的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().and(MovieCollectDao.Properties.Year.gt(2012), MovieCollectDao.Properties.Title.like("我的%")).list();
//or
//查询电影年份小于2012年或者大于2015年的电影
List<MovieCollect> movieCollect = mMovieCollectDao.queryBuilder().or(MovieCollectDao.Properties.Year.lt(2012), MovieCollectDao.Properties.Year.gt(2015)).list();
SQL语句
//查询名字为“羞羞的铁拳”的电影
//使用Dao.queryBuilder().where() 配合 WhereCondition.StringCondition() 实现SQL查询
Query query =
mMovieCollectDao.queryBuilder()
.where(new WhereCondition.StringCondition("TITLE = ?", "羞羞的铁拳")).build();
List<MovieCollect> movieCollect = query.list();
//使用Dao.queryRawCreate() 实现SQL查询
Query query = mMovieCollectDao.queryRawCreate("WHERE TITLE = ?", "羞羞的铁拳");
List<MovieCollect> movieCollect = query.list();
缓存问题
由于GreenDao默认开启了缓存,所以当你调用A查询语句取得X实体,然后对X实体进行修改并更新到数据库,接着再调用A查询语句取得X实体,会发现X实体的内容依旧是修改前的。其实你的修改已经更新到数据库中,只是查询采用了缓存,所以直接返回了第一次查询的实体。
解决方法:查询前先清空缓存,清空方法如下
//清空所有数据表的缓存数据
DaoSession daoSession = DaoManager.getInstance().getDaoSession();
daoSession .clear();
//清空某个数据表的缓存数据
MovieCollectDao movieCollectDao = DaoManager.getInstance().getDaoSession().getMovieCollectDao();
movieCollectDao.detachAll();
加密数据库的步骤:
第一步:
Module下的build.gradle中添加一个库依赖,用于数据库加密。
compile 'net.zetetic:android-database-sqlcipher:3.5.7'//使用加密数据库时需要添加
第二步:
获取DaoSession的过程中,使用getEncryptedWritableDb(“你的密码”)来获取操作的数据库,而不是getWritableDatabase()。
mSQLiteOpenHelper = new MySQLiteOpenHelper(MyApplication.getInstance(), DB_NAME, null);//建库
mDaoMaster = new DaoMaster(mSQLiteOpenHelper.getEncryptedWritableDb("你的密码"));//加密
//mDaoMaster = new DaoMaster(mSQLiteOpenHelper.getWritableDatabase());
mDaoSession = mDaoMaster.newSession();
第三步:
使用上面步骤得到的DaoSession进行具体的数据表操作。
如果运行后报无法加载有关so库的异常,请对项目进行clean和rebuild。
第一步:
新建一个类,继承DaoMaster.DevOpenHelper,重写onUpgrade(Database db, int oldVersion, int newVersion)方法,在该方法中使用MigrationHelper进行数据库升级以及数据迁移。
网上有不少MigrationHelper的源码,这里采用的是https://github.com/yuweiguocn/GreenDaoUpgradeHelper中的MigrationHelper(https://github.com/yuweiguocn/GreenDaoUpgradeHelper/blob/e15c31bf4d9e8bba60645bfd4c98896e37b01db8/library/src/main/java/com/github/yuweiguocn/library/greendao/MigrationHelper.java),它主要是通过创建一个临时表,将旧表的数据迁移到新表中,大家可以去看下源码。
public class MyOpenHelper extends DaoMaster.OpenHelper {
public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
//把需要管理的数据库表DAO作为最后一个参数传入到方法中
MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
@Override
public void onCreateAllTables(Database db, boolean ifNotExists) {
DaoMaster.createAllTables(db, ifNotExists);
}
@Override
public void onDropAllTables(Database db, boolean ifExists) {
DaoMaster.dropAllTables(db, ifExists);
}
}, MovieCollectDao.class);
}
}
然后使用MyOpenHelper替代DaoMaster.DevOpenHelper来进行创建数据库等操作
mSQLiteOpenHelper = new MyOpenHelper(MyApplication.getInstance(), DB_NAME, null);//建库
mDaoMaster = new DaoMaster(mSQLiteOpenHelper.getWritableDatabase());
mDaoSession = mDaoMaster.newSession();
第二步:
在表实体中,调整其中的变量(表字段),一般就是新增/删除/修改字段。注意:
1)新增的字段或修改的字段,其变量类型应使用基础数据类型的包装类,如使用Integer而不是int,避免升级过程中报错。
2)根据MigrationHelper中的代码,升级后,新增的字段和修改的字段,都会默认被赋予null值。
第三步:
将原本自动生成的构造方法以及getter/setter方法删除,重新Build—>Make Project进行生成。
第四步:
修改Module下build.gradle中数据库的版本号schemaVersion ,递增加1即可,最后运行app
greendao {
//数据库版本号,升级时进行修改
schemaVersion 2
daoPackage 'com.dev.base.model.db'
targetGenDir 'src/main/java'
}
# greenDAO开始
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties
# If you do not use SQLCipher:
-dontwarn org.greenrobot.greendao.database.**
# If you do not use RxJava:
-dontwarn rx.**
# greenDAO结束
# 如果按照上面介绍的加入了数据库加密功能,则需添加一下配置
#sqlcipher数据库加密开始
-keep class net.sqlcipher.** {*;}
-keep class net.sqlcipher.database.** {*;}
#sqlcipher数据库加密结束
详细代码请看demo,地址:https://github.com/LJYcoder/DevBase
demo的内容流程,请看《安卓开发框架(MVP+主流框架+基类+工具类)— 开篇》
附上MigrationHelper的代码:
package com.github.yuweiguocn.library.greendao;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.internal.DaoConfig;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* please call {@link #migrate(SQLiteDatabase, Class[])} or {@link #migrate(Database, Class[])}
*
*/
public final class MigrationHelper {
public static boolean DEBUG = false;
private static String TAG = "MigrationHelper";
private static final String SQLITE_MASTER = "sqlite_master";
private static final String SQLITE_TEMP_MASTER = "sqlite_temp_master";
private static WeakReference<ReCreateAllTableListener> weakListener;
public interface ReCreateAllTableListener{
void onCreateAllTables(Database db, boolean ifNotExists);
void onDropAllTables(Database db, boolean ifExists);
}
public static void migrate(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
printLog("【The Old Database Version】" + db.getVersion());
Database database = new StandardDatabase(db);
migrate(database, daoClasses);
}
public static void migrate(SQLiteDatabase db, ReCreateAllTableListener listener, Class<? extends AbstractDao<?, ?>>... daoClasses) {
weakListener = new WeakReference<>(listener);
migrate(db, daoClasses);
}
public static void migrate(Database database, ReCreateAllTableListener listener, Class<? extends AbstractDao<?, ?>>... daoClasses) {
weakListener = new WeakReference<>(listener);
migrate(database, daoClasses);
}
public static void migrate(Database database, Class<? extends AbstractDao<?, ?>>... daoClasses) {
printLog("【Generate temp table】start");
generateTempTables(database, daoClasses);
printLog("【Generate temp table】complete");
ReCreateAllTableListener listener = null;
if (weakListener != null) {
listener = weakListener.get();
}
if (listener != null) {
listener.onDropAllTables(database, true);
printLog("【Drop all table by listener】");
listener.onCreateAllTables(database, false);
printLog("【Create all table by listener】");
} else {
dropAllTables(database, true, daoClasses);
createAllTables(database, false, daoClasses);
}
printLog("【Restore data】start");
restoreData(database, daoClasses);
printLog("【Restore data】complete");
}
private static void generateTempTables(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for (int i = 0; i < daoClasses.length; i++) {
String tempTableName = null;
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String tableName = daoConfig.tablename;
if (!isTableExists(db, false, tableName)) {
printLog("【New Table】" + tableName);
continue;
}
try {
tempTableName = daoConfig.tablename.concat("_TEMP");
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE IF EXISTS ").append(tempTableName).append(";");
db.execSQL(dropTableStringBuilder.toString());
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("CREATE TEMPORARY TABLE ").append(tempTableName);
insertTableStringBuilder.append(" AS SELECT * FROM `").append(tableName).append("`;");
db.execSQL(insertTableStringBuilder.toString());
printLog("【Table】" + tableName +"\n ---Columns-->"+getColumnsStr(daoConfig));
printLog("【Generate temp table】" + tempTableName);
} catch (SQLException e) {
Log.e(TAG, "【Failed to generate temp table】" + tempTableName, e);
}
}
}
private static boolean isTableExists(Database db, boolean isTemp, String tableName) {
if (db == null || TextUtils.isEmpty(tableName)) {
return false;
}
String dbName = isTemp ? SQLITE_TEMP_MASTER : SQLITE_MASTER;
String sql = "SELECT COUNT(*) FROM `" + dbName + "` WHERE type = ? AND name = ?";
Cursor cursor=null;
int count = 0;
try {
cursor = db.rawQuery(sql, new String[]{"table", tableName});
if (cursor == null || !cursor.moveToFirst()) {
return false;
}
count = cursor.getInt(0);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
}
return count > 0;
}
private static String getColumnsStr(DaoConfig daoConfig) {
if (daoConfig == null) {
return "no columns";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < daoConfig.allColumns.length; i++) {
builder.append(daoConfig.allColumns[i]);
builder.append(",");
}
if (builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
private static void dropAllTables(Database db, boolean ifExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
reflectMethod(db, "dropTable", ifExists, daoClasses);
printLog("【Drop all table by reflect】");
}
private static void createAllTables(Database db, boolean ifNotExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
reflectMethod(db, "createTable", ifNotExists, daoClasses);
printLog("【Create all table by reflect】");
}
/**
* dao class already define the sql exec method, so just invoke it
*/
private static void reflectMethod(Database db, String methodName, boolean isExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
if (daoClasses.length < 1) {
return;
}
try {
for (Class cls : daoClasses) {
Method method = cls.getDeclaredMethod(methodName, Database.class, boolean.class);
method.invoke(null, db, isExists);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private static void restoreData(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for (int i = 0; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
if (!isTableExists(db, true, tempTableName)) {
continue;
}
try {
// get all columns from tempTable, take careful to use the columns list
List<TableInfo> newTableInfos = TableInfo.getTableInfo(db, tableName);
List<TableInfo> tempTableInfos = TableInfo.getTableInfo(db, tempTableName);
ArrayList<String> selectColumns = new ArrayList<>(newTableInfos.size());
ArrayList<String> intoColumns = new ArrayList<>(newTableInfos.size());
for (TableInfo tableInfo : tempTableInfos) {
if (newTableInfos.contains(tableInfo)) {
String column = '`' + tableInfo.name + '`';
intoColumns.add(column);
selectColumns.add(column);
}
}
// NOT NULL columns list
for (TableInfo tableInfo : newTableInfos) {
if (tableInfo.notnull && !tempTableInfos.contains(tableInfo)) {
String column = '`' + tableInfo.name + '`';
intoColumns.add(column);
String value;
if (tableInfo.dfltValue != null) {
value = "'" + tableInfo.dfltValue + "' AS ";
} else {
value = "'' AS ";
}
selectColumns.add(value + column);
}
}
if (intoColumns.size() != 0) {
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("REPLACE INTO `").append(tableName).append("` (");
insertTableStringBuilder.append(TextUtils.join(",", intoColumns));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", selectColumns));
insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");
db.execSQL(insertTableStringBuilder.toString());
printLog("【Restore data】 to " + tableName);
}
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);
db.execSQL(dropTableStringBuilder.toString());
printLog("【Drop temp table】" + tempTableName);
} catch (SQLException e) {
Log.e(TAG, "【Failed to restore data from temp table 】" + tempTableName, e);
}
}
}
private static List<String> getColumns(Database db, String tableName) {
List<String> columns = null;
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 0", null);
if (null != cursor && cursor.getColumnCount() > 0) {
columns = Arrays.asList(cursor.getColumnNames());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
if (null == columns)
columns = new ArrayList<>();
}
return columns;
}
private static void printLog(String info){
if(DEBUG){
Log.d(TAG, info);
}
}
private static class TableInfo {
int cid;
String name;
String type;
boolean notnull;
String dfltValue;
boolean pk;
@Override
public boolean equals(Object o) {
return this == o
|| o != null
&& getClass() == o.getClass()
&& name.equals(((TableInfo) o).name);
}
@Override
public String toString() {
return "TableInfo{" +
"cid=" + cid +
", name='" + name + '\'' +
", type='" + type + '\'' +
", notnull=" + notnull +
", dfltValue='" + dfltValue + '\'' +
", pk=" + pk +
'}';
}
private static List<TableInfo> getTableInfo(Database db, String tableName) {
String sql = "PRAGMA table_info(`" + tableName + "`)";
printLog(sql);
Cursor cursor = db.rawQuery(sql, null);
if (cursor == null)
return new ArrayList<>();
TableInfo tableInfo;
List<TableInfo> tableInfos = new ArrayList<>();
while (cursor.moveToNext()) {
tableInfo = new TableInfo();
tableInfo.cid = cursor.getInt(0);
tableInfo.name = cursor.getString(1);
tableInfo.type = cursor.getString(2);
tableInfo.notnull = cursor.getInt(3) == 1;
tableInfo.dfltValue = cursor.getString(4);
tableInfo.pk = cursor.getInt(5) == 1;
tableInfos.add(tableInfo);
// printLog(tableName + ":" + tableInfo);
}
cursor.close();
return tableInfos;
}
}
}