本文在CSDN博客首发
转载请注明出处
http://blog.csdn.net/u011071427/article/details/54574171
本文出自Allen李的博客
GrenDao的深入使用
在本文中将会讲解一些使用GreenDao的FAQ
混淆
### greenDAO 3
-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 2
-keepclassmembers class * extends de.greenrobot.dao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties
GreenDao修改生成目录
//目录设置
sourceSets {
main {
java.srcDirs = ['src/main/java', 'src/main/greendao']
jniLibs.srcDirs=['./libs']
}
}
//GreenDao设置
greendao{
targetGenDir 'src/main/greendao'
daoPackage 'com.greendao'
schemaVersion 1
}
数据库升级
GreenDao数据库现在唯一不好的可能就是升级数据库了。
1.先看DaoMaster生成的代码。
/** 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);
}
}
2.如果自定义的SqliteOpenHelper是继承自DevOpenHelper,那么在升级数据的时候会把所有表删除掉,然后创建新的表。
这种方式进行升级数据库,会照成原始数据的缺失,所以实际情况中是不运行出现这种升级方式的,这种方式使用于测试期,也就是版本未上线期间。
那么如果我们要进行数据库的保留数据升级,我们应该怎么做呢?
1.首先我们需要重写onUpgrade方法,那么先自定义SqliteOpenHeler.
public class MySqlLiteOpenHelper extends DaoMaster.OpenHelper{
public MySqlLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greendao","oldVersion:"+oldVersion+",newVersion"+newVersion);
switch (oldVersion){
case 1:
db.execSQL("SQL语句");
break;
case 2:
db.execSQL("SQL语句");
break;
case 3:
db.execSQL("SQL语句");
break;
…………
}
}
}
2.以前确实是这么写的,数据库的升级也的确是这么搞的,但是当项目上线以后,数据库庞大,迭代版本次数多,每一次迭代,都需要升级数据库,Swith语句越来越庞大。我们该怎么办呢?
3.先提供思路给大家参考(PS:不是标准答案)。
(1)首先创建临时表(数据格式和原表一模一样)。
(2)把当前表的数据插入到临时表中去。
(3)删除掉原表,创建新表。
(4)把临时表数据插入到新表中去,然后删除临时表。
在这样基础上,可以保留原数据进行升级数据库。
4.本着拿来主义,因为国外大牛已经有对这些进行封装,所以直接把代码贴出来了
public class MigrationHelper {
private static final String CONVERSION_CLASS_NOT_FOUND_EXCEPTION = "MIGRATION HELPER - CLASS DOESN'T MATCH WITH THE CURRENT PARAMETERS";
private static MigrationHelper instance;
public static MigrationHelper getInstance() {
if (instance == null) {
instance = new MigrationHelper();
}
return instance;
}
private static List<String> getColumns(Database db, String tableName) {
List<String> columns = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 1", null);
if (cursor != null) {
columns = new ArrayList<>(Arrays.asList(cursor.getColumnNames()));
}
} catch (Exception e) {
Log.v(tableName, e.getMessage(), e);
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
}
return columns;
}
public void migrate(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
generateTempTables(db, daoClasses);
DaoMaster.dropAllTables(db, true);
DaoMaster.createAllTables(db, false);
restoreData(db, daoClasses);
}
private void generateTempTables(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for (int i = 0; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String divider = "";
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
ArrayList<String> properties = new ArrayList<>();
StringBuilder createTableStringBuilder = new StringBuilder();
createTableStringBuilder.append("CREATE TABLE ").append(tempTableName).append(" (");
for (int j = 0; j < daoConfig.properties.length; j++) {
String columnName = daoConfig.properties[j].columnName;
if (getColumns(db, tableName).contains(columnName)) {
properties.add(columnName);
String type = null;
try {
type = getTypeByClass(daoConfig.properties[j].type);
} catch (Exception exception) {
exception.printStackTrace();
}
createTableStringBuilder.append(divider).append(columnName).append(" ").append(type);
if (daoConfig.properties[j].primaryKey) {
createTableStringBuilder.append(" PRIMARY KEY");
}
divider = ",";
}
}
createTableStringBuilder.append(");");
Log.i("lxq", "创建临时表的SQL语句: " + createTableStringBuilder.toString());
db.execSQL(createTableStringBuilder.toString());
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("INSERT INTO ").append(tempTableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(" FROM ").append(tableName).append(";");
Log.i("lxq", "在临时表插入数据的SQL语句:" + insertTableStringBuilder.toString());
db.execSQL(insertTableStringBuilder.toString());
}
}
private 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");
ArrayList<String> properties = new ArrayList();
ArrayList<String> propertiesQuery = new ArrayList();
for (int j = 0; j < daoConfig.properties.length; j++) {
String columnName = daoConfig.properties[j].columnName;
if (getColumns(db, tempTableName).contains(columnName)) {
properties.add(columnName);
propertiesQuery.add(columnName);
} else {
try {
if (getTypeByClass(daoConfig.properties[j].type).equals("INTEGER")) {
propertiesQuery.add("0 as " + columnName);
properties.add(columnName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", propertiesQuery));
insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);
Log.i("lxq", "插入正式表的SQL语句:" + insertTableStringBuilder.toString());
Log.i("lxq", "销毁临时表的SQL语句:" + dropTableStringBuilder.toString());
db.execSQL(insertTableStringBuilder.toString());
db.execSQL(dropTableStringBuilder.toString());
}
}
private String getTypeByClass(Class<?> type) throws Exception {
if (type.equals(String.class)) {
return "TEXT";
}
if (type.equals(Long.class) || type.equals(Integer.class) || type.equals(long.class) || type.equals(int.class)) {
return "INTEGER";
}
if (type.equals(Boolean.class) || type.equals(boolean.class)) {
return "BOOLEAN";
}
Exception exception = new Exception(CONVERSION_CLASS_NOT_FOUND_EXCEPTION.concat(" - Class: ").concat(type.toString()));
exception.printStackTrace();
throw exception;
}
}
5.使用以上工具类的时候,onUpgrade方法就变成以下这么简单了。
public class MySqlLiteOpenHelper extends DaoMaster.OpenHelper{
public MySqlLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("lxq","oldVersion:"+oldVersion+",newVersion"+newVersion);
MigrationHelper.getInstance().migrate(db,UserDao.class);
}
}
6.使用注意:要把为了不忘记某些XXDao.class,最好把所有的XXDao.class丢进去。
GreenDao的封装
GreenDao的简单二次封装
public class DaoManager {
private static String DB_NAME = "test.db";
private static DaoManager mDaoManager;
private static MySqlLiteOpenHelper mySqlLiteOpenHelper;
private static DaoSession mDaoSession;
private static Database mDatabase;
private DaoManager() {}
public static DaoManager getInstance(){
if (mDaoManager == null){
synchronized (DaoManager.class){
if (mDaoManager == null){
mDaoManager = new DaoManager();
}
}
}
return mDaoManager;
}
public static void init(Context context){
mySqlLiteOpenHelper = new MySqlLiteOpenHelper(context,DB_NAME,null);
mDatabase = mySqlLiteOpenHelper.getWritableDb();
mDaoSession = new DaoMaster(mDatabase).newSession();
}
public DaoSession getDaoSession(){
return mDaoSession;
}
}
这个管理类中,我把DaoSession给暴漏出来,然后可以通过DaoSession获取XXDao,然后进行操作数据库。下面可以看我的例子:
public class UserDaoManagr implements IDao<User> {
private DaoSession mDaoSession = DaoManager.getInstance().getDaoSession();
@Override
public boolean insert(User user) {
return mDaoSession.getUserDao()
.insert(user) > 0 ? true : false;
}
@Override
public boolean delete(User user) {
try {
mDaoSession.getUserDao()
.delete(user);
} catch (Exception e) {
Log.e("lxq", "删除失败");
return false;
}
return true;
}
@Override
public boolean update(User user) {
try {
mDaoSession.getUserDao()
.update(user);
} catch (Exception e) {
Log.e("lxq", "更新失败");
return false;
}
return true;
}
@Override
public List<User> queryAll() {
return mDaoSession.getUserDao()
.loadAll();
}
@Override
public User queryById(long id) {
return mDaoSession.getUserDao()
.loadByRowId(id);
}
@Override
public List<User> queryByObj(String where, String... params) {
return mDaoSession.getUserDao()
.queryRaw(where, params);
}
public User queryByName(String name) {
return mDaoSession.getUserDao()
.queryBuilder()
.where(UserDao.Properties.Name.eq(name))
.build()
.unique();
}
}
要想使用DaoManager,别忘记在Application中初始化。
DaoManager.init(this);