GreenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案
该框架具有以下优点
1、一个精简的库
2、性能最大化
3、内存开销最小化
4、易于使用的 APIs
5、对 Android 进行高度优化
使用方法
1.导入相关类库 mudule的gradle下配置
compile'org.greenrobot:greendao:3.0.1' compile'org.greenrobot:greendao-generator:3.0.0'
2.导入greendao插件 project的gradle下配置
buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.0' classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0' } }
3.自定义路径mudule的gradle下配置
apply plugin: 'org.greenrobot.greendao'
android{
greendao { schemaVersion 11//数据库版本号,升级的时候使用 daoPackage 'com.binzhi.testgreendao.gen'//对应项目下生成的包名 targetGenDir 'src/main/java'//生成目录,默认使用这个
}
}
4.创建一个实体类
@Entity public class User { @Id private Long id; private String name; @Transient private int tempUsageCount; // not persisted }
5.点击上面的Make Project (绿色锤子按钮)
通过上面使用方式我们可以获取DaoMaster 、DaoSession、Dao类
Dao为对应类生成的数据,DaoMaster 操作数据库表格 DaoSession衔接数据库和具体的dao数据,操作数据的直接类
6.使用方法
public class MyApplication extends Application { public static MyApplication instances; private static SQLiteDatabase db; private static DaoMaster mDaoMaster; private static DaoSession mDaoSession; private static MyOpenHelper mHelper; @Override public void onCreate() { super.onCreate(); instances = this; initDatabase(); } //获取上下文 public static MyApplication getInstances(){ return instances; } public static void initDatabase() { // 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。 // 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。 // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。这个类为daomaster内部类,实际升级我们要自己定义 // 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级,也就是自定义自己的数据库 // mHelper = new DaoMaster.DevOpenHelper(instances, "cache-db", null); mHelper = new MyOpenHelper(instances,"cache-db",null); db = mHelper.getWritableDatabase(); // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。 mDaoMaster = new DaoMaster(db); mDaoSession = mDaoMaster.newSession(); } public static DaoSession getDaoSession() { return mDaoSession; } public static SQLiteDatabase getDb() { return db; } }
Activity中通过mDaoSession 获取da实体类便可以进行相关操作
mUserDao = MyApplication.getInstances().getDaoSession().getUserDao();
//读取数据
Listusers = mStudentDao.loadAll();
//插入数据
Teacher teacher=new Teacher(null,"haha",20); mTeacherDao.insert(teacher);
//删除
mTeacherDao.deleteAll();
//根据条件查询 常用查询方法 eq等于 le小于 gt大于
7.数据库升级
首先需要明白数据库的升级的逻辑,大致情况为
1:将表A重新命名:例如重新命名为:temp_A(或者创建临时表作为衔接也可以) 2:创建新标A 3: 将temp_A中的数据【也就是更新前的数据】插入到新表A
对于不同的版本号升级,还要处理不同情况的问题,实际操作流程也比较繁琐,这里献上已经封装好的升级方法,以后升级使用此类即可
数据库升级迁移方法类
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; } 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"); ArrayListproperties = 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) { } createTableStringBuilder.append(divider).append(columnName).append(" ").append(type); if (daoConfig.properties[j].primaryKey) { createTableStringBuilder.append(" PRIMARY KEY"); } divider = ","; } } createTableStringBuilder.append(");"); 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(";"); 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 properties = 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); } } StringBuilder insertTableStringBuilder = new StringBuilder(); insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" ("); insertTableStringBuilder.append(TextUtils.join(",", properties)); insertTableStringBuilder.append(") SELECT "); insertTableStringBuilder.append(TextUtils.join(",", properties)); insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";"); StringBuilder dropTableStringBuilder = new StringBuilder(); dropTableStringBuilder.append("DROP TABLE ").append(tempTableName); 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)) { return "INTEGER"; } if (type.equals(Boolean.class)) { return "BOOLEAN"; } Exception exception = new Exception(CONVERSION_CLASS_NOT_FOUND_EXCEPTION.concat(" - Class: ").concat(type.toString())); throw exception; } private static List getColumns(Database db, String tableName) { List 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; } }
初始化的时候一定要记得使用自定义的OpenHelper 而不是生成默认的,默认的更新不保存数据!
public class MyOpenHelper extends DaoMaster.OpenHelper { public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) { super(context, name, factory); }
//第一次创建新表的时候才会调用
@Override public void onCreate(Database db) { super.onCreate(db); }
//已有数据库,升级的时候以后都走这个方法
@Override public void onUpgrade(Database db, int oldVersion, int newVersion) { //更数据库
//这里根据自己更新的表实体类,逐个传入到参数内//切记不能重复调用这个方法来更新表,而是一次性调用传入所需要的全部实体类 MigrationHelper.getInstance().migrate(db,StudentDao.class,TeacherDao.class,UserDao.class);
}
}
最后记得在gradle中把版本号调高才会升级
参考文献