greenDao是一个开源的AndroidORM对象关系映射型数据库操作框架,它的使用效率要高于其他ORM型数据库框架。
greenDao官网:http://greenrobot.org/greendao/
greenDao GitHub地址:https://github.com/greenrobot/greenDAO
greenDao核心类:
DaoMaster:
DaoMaster保存了数据库对象和管理DAO类的classes,其提供了一些静态方法创建和删除表,内部类OpenHelper和DevOpenHelper 实现了SQLiteOpenHelper并创建数据库的框架。
DaoSession:
管理所有可用的DAO对象,可以通过getter方法获得。DaoSession还提供了一些通用的持久性方法比如插入、加载、更新,刷新和删除实体。
DAOs:
数据访问对象,每一个实体类都有对应的greenDAO对象。
Entities:
实体类对象
其中,在greenDao中,Dao是由Entitie 编译后自动生成的。
使用配置:
在app的build.gradle中添加
apply plugin: 'org.greenrobot.greendao'
greendao { schemaVersion 2 //数据库版本 daoPackage 'com.example.entity.gen'//dao自动生成的目录 targetGenDir 'src/main/java'//dao所在文件 } buildscript { repositories { mavenCentral() } dependencies { classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0' } }
dependencies { compile 'org.greenrobot:greendao-generator:3.1.0' compile 'org.greenrobot:greendao:3.1.0' }
经过上面的配置,GreenDao就配置完成了。
基本使用:
greenDao3采用注解的方式对Entity配置,一个数据表对应一个Entity。
greenDao对数据库进行操作时需要用到DaoMaster和DaoSession,建议把这个两个对象的获取方法写到Application中,可以保证其单例调用。
/** * 取得DaoMaster * * @param context * @return */ public static DaoMaster getDaoMaster(Context context) { if (daoMaster == null) { DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context,DatabasePath, null); daoMaster = new DaoMaster(helper.getWritableDatabase()); } return daoMaster; } /** * 取得DaoSession * * @param context * @return */ public static DaoSession getDaoSession(Context context) { if (daoSession == null) { if (daoMaster == null) { daoMaster = getDaoMaster(context); } daoSession = daoMaster.newSession(); } return daoSession; }
例如下面有个表:
我们可以新建一个Entity存入对应字段,然后make project就可以自动生成dao文件:
@Entity(nameInDb = "FoowwReminders", createInDb = false) public class FoowwRemindersEntity implements Serializable { private static final long serialVersionUID = 8675420969232321045L; @Property(nameInDb = "PKFoowwReminder") @Convert(converter = UUID2BytesConverter.class, columnType = byte[].class) public UUID PKFoowwReminder; @Property(nameInDb = "FoowwReminderType") public int FoowwReminderType; @Property(nameInDb = "PKObject") @Convert(converter = UUID2BytesConverter.class, columnType = byte[].class) public UUID PKObject; @Property(nameInDb = "FoowwReminderContent") public String FoowwReminderContent; @Property(nameInDb = "FoowwReminderStartDate") public String FoowwReminderStartDate; @Property(nameInDb = "FoowwReminderEndDate") public String FoowwReminderEndDate; @Property(nameInDb = "PKCreator") @Convert(converter = UUID2BytesConverter.class, columnType = byte[].class) public UUID PKCreator; @Property(nameInDb = "CreateTime") public String CreateTime; @Property(nameInDb = "AdvanceTime") public int AdvanceTime; @Property(nameInDb = "UpdateTime") public String UpdateTime; @Property(nameInDb = "DeleteStatus") public int DeleteStatus; }
greenDao3中,用注解来对字段进行设定。具体
greenDao中对数据库操作都要使用数据表对应的dao进行操作。
基本增删改查:
FoowwRemindersEntity reminder = new FoowwRemindersEntity();
String createTime = Utility.GetTimeNow();
reminder.CreateTime = createTime;
reminder.AdvanceTime = getAdvanceMin(tvAdvanceTime.getText().toString());
reminder.DeleteStatus = 0;
reminder.FoowwReminderContent = etReminder.getText().toString().trim();
reminder.FoowwReminderEndDate = reminderEndTime;
reminder.FoowwReminderStartDate = reminderStartTime;
UUID pkReminder = UUID.randomUUID();
reminder.PKFoowwReminder = pkReminder;
reminder.PKCreator = App.PKUser;
reminder.PKObject = null;
reminder.UpdateTime = createTime;
reminder.FoowwReminderType = 0;
reminder.PushStatus = 0;
//插入
App.getDaoSession(context).insert(reminder);
//删除,需要设置主键
App.getDaoSession(context).delete(reminder);
//修改,需要设置主键
App.getDaoSession(context).update(reminder);
//查询一
QueryBuilder db = reminder.queryBuilder();
List<FoowwRemindersEntity> list = db.where(FoowwRemindersEntityDao.Properties.HouseType.eq(1)).list();
//查询二
List<FoowwRemindersEntity> list = (List<FoowwRemindersEntity>)App.getDaoSession(context).getDao(FoowwRemindersEntity.class).queryRaw("where houseType=1");
下面是我封装的一些操作方法:
Application的继承类App:
/**
* 取得DaoMaster
*
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context) {
if (daoMaster == null) {
DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context,DatabasePath, null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
}
return daoMaster;
}
/**
* 取得DaoSession
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
daoMaster = getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
public interface ISQLiteOperate {
boolean execSQL(String sql);
boolean execSQLList(List<String> sqlList);
boolean execSQLs(List<String[]> sqlList);
boolean execSQLIgnoreError(List<String> sqlList);
Cursor query(String sql);
Cursor query(String sql, String[] params);
void close();
<T> void insert(T entity);
<T> void insertInTx(Class<T> entityClass,T... entities);
<T> void insertOrReplace(T entity);
<T> void delete(T entity);
<T> void deleteInTx(Class<T> entityClass,T... entities);
<T> void update(T entity);
<T> void updateInTx(Class<T> entityClass,T... entities);
void runInTx(Runnable runnable);
<T> QueryBuilder<T> queryBuilder(Class<T> entityClass);
<T> List<T> queryRaw(Class<T> entityClass, String conditions);
DaoSession getDaoSession();
}
SQLiteDataProxyForGreenDao具体实现类:
public class SQLiteDataProxyForGreenDao implements ISQLiteOperate{
private static DaoMaster mDaoMaster;
private static DaoSession mDaoSession;
private static SQLiteDataProxyForGreenDao proxy;
Cursor cursor;
public static SQLiteDataProxyForGreenDao getSQLiteProxy(Context context) {
if (proxy == null) {
synchronized (SQLiteDataProxyForGreenDao.class) {
if (proxy == null) {
proxy = new SQLiteDataProxyForGreenDao();
mDaoMaster = App.getDaoMaster(context);
mDaoSession = App.getDaoSession(context);
}
}
}
return proxy;
}
@Override
public boolean execSQL(String sql) {
boolean result = true;
try {
mDaoMaster.getDatabase().execSQL(sql);
} catch (Exception e) {
Log.e("SQLERROR", "execSQL:" + e.getMessage() + sql);
result = false;
}
return result;
}
@Override
public boolean execSQLList(List<String> sqlList) {
boolean result = true;
String currentSqlString = "";
try {
mDaoMaster.getDatabase().beginTransaction();
for (String sql : sqlList) {
currentSqlString = sql;
mDaoMaster.getDatabase().execSQL(sql);
}
mDaoMaster.getDatabase().setTransactionSuccessful();
result = true;
} catch (Exception e) {
result = false;
Log.e("SQLERROR", "execSQLList: " + e.getMessage() + currentSqlString);
} finally {
mDaoMaster.getDatabase().endTransaction();
}
return result;
}
@Override
public boolean execSQLs(final List<String[]> sqlList) {
boolean result = true;
String currentSql = "";
Cursor curCount;
try {
mDaoMaster.getDatabase().beginTransaction();
for (String[] arr : sqlList) {
currentSql = arr[0];
curCount = mDaoMaster.getDatabase().rawQuery(arr[0], null);
curCount.moveToFirst();
int count = curCount.getInt(0);
curCount.close();
if (count == 0) {
if (arr[1] != null && arr[1].length() > 0) {
currentSql = arr[1];
mDaoMaster.getDatabase().execSQL(arr[1]);
}
} else {
if (arr.length > 2 && arr[2] != null && arr[2].length() > 0) {
currentSql = arr[2];
mDaoMaster.getDatabase().execSQL(arr[2]);
}
}
}
mDaoMaster.getDatabase().setTransactionSuccessful();
result = true;
} catch (Exception e) {
Log.e("SQLERROR", "execSQLs: " + currentSql + e.getMessage());
result = false;
} finally {
mDaoMaster.getDatabase().endTransaction();
curCount.closed();
}
return result;
}
@Override
public boolean execSQLIgnoreError(List<String> sqlList) {
mDaoMaster.getDatabase().beginTransaction();
for (String sql : sqlList) {
try {
mDaoMaster.getDatabase().execSQL(sql);
} catch (Exception e) {
Log.e("SQLERROR", "execSQLIgnoreError: " + sql + e.getMessage());
}
// mDaoMaster.getDatabase().execSQL(sql);
}
mDaoMaster.getDatabase().setTransactionSuccessful();
mDaoMaster.getDatabase().endTransaction();
return false;
}
@Override
public Cursor query(String sql) {
return query(sql,null);
}
@Override
public Cursor query(String sql, String[] params) {
cursor = mDaoMaster.getDatabase().rawQuery(sql, params);
return cursor;
}
@Override
public void close() {
if(cursor != null){
cursor.closed();
}
}
@Override
public <T> void insert(T entity){
mDaoSession.insert(entity);
}
@Override
public <T> void insertInTx(Class<T> entityClass,T... entities) {
//TODO
//mDaoSession.getDao(entityClass).insert(entities);
}
@Override
public void runInTx(Runnable runnable) {
mDaoSession.runInTx(runnable);
}
@Override
public <T> void insertOrReplace(T entity) {
mDaoSession.insertOrReplace(entity);
}
@Override
public <T> void delete(T entity) {
mDaoSession.delete(entity);
}
@Override
public <T> void deleteInTx(Class<T> entityClass,T... entities) {
//TODO
}
@Override
public <T> void update(T entity) {
mDaoSession.update(entity);
}
@Override
public <T> void updateInTx(Class<T> entityClass,T... entities) {
//TODO
}
@Override
public <T> QueryBuilder<T> queryBuilder(Class<T> entityClass) {
return mDaoSession.queryBuilder(entityClass);
}
@Override
public <T> List<T> queryRaw(Class<T> entityClass, String conditions) {
List<T> list = (List<T>) mDaoSession.getDao(entityClass).queryRaw(conditions);
return list;
}
@Override
public DaoSession getDaoSession() {
return mDaoSession;
}
}
DBManager实际调用的类:
public class DBManager {
private static final int BUFFERSIZE = 8192;
private Context context;
private ISQLiteOperate sqLiteOperate;
public DBManager(Context context){
this.context = context;
sqLiteOperate = SQLiteDataProxyForGreenDao.getSQLiteProxy(context);
}
public void asyncExecSQL(final String sql){
new Thread(new Runnable() {
@Override
public void run() {
sqLiteOperate.execSQL(sql);
}
}).start();
}
public void asyncExecSQLList(final List<String> sqlList){
new Thread(new Runnable() {
@Override
public void run() {
sqLiteOperate.execSQLList(sqlList);
}
}).start();
}
public void asyncExecSQLs(final List<String[]> sqlList){
new Thread(new Runnable() {
@Override
public void run() {
sqLiteOperate.execSQLs(sqlList);
}
}).start();
}
public void asyncExecSQLIgnoreError(final List<String> sqlList){
new Thread(new Runnable() {
@Override
public void run() {
sqLiteOperate.execSQLIgnoreError(sqlList);
}
}).start();
}
public boolean execSQL(String sql){
return sqLiteOperate.execSQL(sql);
}
public boolean execSQLList(List<String> sqlList){
return sqLiteOperate.execSQLList(sqlList);
}
public boolean execSQLs(List<String[]> sqlList){
return sqLiteOperate.execSQLs(sqlList);
}
public boolean execSQLIgnoreError(List<String> sqlList){
return sqLiteOperate.execSQLIgnoreError(sqlList);
}
/**
* 每调用一次都需要手动close一次
* @param sql
* @return
*/
public Cursor query(String sql){
return sqLiteOperate.query(sql);
}
/**
* 每调用一次都需要手动close一次
* @param sql
* @param params
* @return
*/
public Cursor query(String sql, String[] params){
return sqLiteOperate.query(sql, params);
}
public void close(){
sqLiteOperate.close();
}
public <T> void insert(T entity){
sqLiteOperate.insert(entity);
}
public <T> void insertInTx(Class<T> entityClass,T... entities) {
//TODO
//mDaoSession.getDao(entityClass).insert(entities);
}
public void runInTx(Runnable runnable) {
sqLiteOperate.runInTx(runnable);
}
public <T> void insertOrReplace(T entity) {
sqLiteOperate.insertOrReplace(entity);
}
public <T> void delete(T entity) {
sqLiteOperate.delete(entity);
}
public <T> void deleteInTx(Class<T> entityClass,T... entities) {
//TODO
}
public <T> void update(T entity) {
sqLiteOperate.update(entity);
}
public <T> void updateInTx(Class<T> entityClass,T... entities) {
//TODO
}
public <T> QueryBuilder<T> queryBuilder(Class<T> entityClass){
return sqLiteOperate.queryBuilder(entityClass);
}
/**
* 相当于Select * from "entityClass" + "....conditions...."
* @param entityClass
* @param conditions
* @param <T>
* @return
*/
public <T> List<T> queryRaw(Class<T> entityClass,String conditions) {
return sqLiteOperate.queryRaw(entityClass,conditions);
}
public DaoSession getDaoSession() {
return sqLiteOperate.getDaoSession();
}
public static boolean InitializeDatabase(Context context) {
try {
File oldDbFile = new File(App.DatabasePath);
if (oldDbFile.exists()) {
return true;
}
InputStream is = context.getResources().openRawResource(R.raw.foowwlite);
FileOutputStream fos = new FileOutputStream(App.DatabasePath);
byte[] buffer = new byte[BUFFERSIZE];
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
is.close();
return true;
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
}
public static boolean UpdateDatabase(Context context) {
try {
File oldDbFile = new File(App.DatabasePath);
if (oldDbFile.exists()){
oldDbFile.delete();
}
InputStream is = context.getResources().openRawResource(R.raw.foowwlite);
FileOutputStream fos = new FileOutputStream(App.DatabasePath);
byte[] buffer = new byte[BUFFERSIZE];
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
is.close();
return true;
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
}
}