Giuthub:https://github.com/greenrobot/greenDAO
greenDao官网:http://greenrobot.org/greendao/
greenDao2的引入地址(Github上面已经更新到greenDao3)
compile'org.greenrobot:greendao:3.0.1'
compile'org.greenrobot:greendao-generator:3.0.0'
2.在build.gradle中进行配置:
apply plugin: 'org.greenrobot.greendao'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'
}
}
3.自定义路径
greendao {
schemaVersion 1
daoPackage 'com.anye.greendao.gen'
targetGenDir 'src/main/java'
}
schemaVersion–> 指定数据库schema版本号,迁移等操作会用到;
daoPackage –> dao的包名,包名默认是entity所在的包;
targetGenDir –> 生成数据库文件的目录;
在创建实体类后make工程,相关的master类和session类和dao类都会生成在这个文件下
(一) @Entity 定义实体
@nameInDb 在数据库中的名字,如不写则为实体中类名
@indexes 索引
@createInDb 是否创建表,默认为true,false时不创建
@schema 指定架构名称为实体
@active 无论是更新生成都刷新
(二) @Id
(三) @NotNull 不为null
(四) @Unique 唯一约束
(五) @ToMany 一对多
(六) @OrderBy 排序
(七) @ToOne 一对一
(八) @Transient 不存储在数据库中
(九) @generated 由greendao产生的构造函数或方法
本文将从 数据库基础接口抽离,greenDao知识,greenDao的个性化基类封装和一个简单示例 为序向各位读者说明一下作者的思路以及实践。
数据库操作无非就是 增、删、改、查、事务,好接下来就可以细化了
public interface IDataBase{
boolean insert(T t);
boolean delete(T t);
boolean deleteByKey(K k);
boolean deleteList(List mList);
boolean deleteByKeyInTx(K... keys);
//采用事务操作,删除key[ ]中每个key所对应的实体,并返回一个空的Observable
boolean deleteAll();
boolean insertOrReplace(@NonNull T t);
boolean update(T t);
boolean updateInTx(T... t);
boolean updateList(List mList);
T selectByPrimaryKey(K key);
List loadAll();
boolean refresh(T t);
/**
* 清理缓存
*/
void clearDaoSession();
/**
* Delete all tables and content from our database
*/
boolean dropDatabase();
/**
* 事务
*/
void runInTx(Runnable runnable);
/**
* 添加集合
*
* @param mList
*/
boolean insertList(List mList);
/**
* 添加或更新集合
*
* @param mList
*/
boolean insertOrReplaceList(List mList);
/**
* 自定义查询
*
* @return
*/
QueryBuilder getQueryBuilder();
/**
* @param where
* @param selectionArg
* @return
*/
List queryRaw(String where, String... selectionArg);
}
public abstract class AbstractDatabaseManager implements IDataBase {
private static final String DEFAULT_DATABASE_NAME = Constants.DEFAULT_DB_NAME;
/**
* The Android Activity reference for access to DatabaseManager.
*/
private static DaoMaster.DevOpenHelper mHelper;
protected static DaoSession daoSession;
/**
* 初始化OpenHelper
* @param context
*/
public static void initOpenHelper(@NonNull Context context) {
mHelper = getOpenHelper(context, DEFAULT_DATABASE_NAME);
openWritableDb();
}
/**
* 初始化OpenHelper *
* @param context
* @param dataBaseName
*/
public static void initOpenHelper(@NonNull Context context, @NonNull String dataBaseName) {
mHelper = getOpenHelper(context, dataBaseName);
openWritableDb();
}
public static DaoSession getDaoSession() {
return daoSession;
}
/** * Query for readable DB */
protected static void openReadableDb() throws SQLiteException {
daoSession = new DaoMaster(getReadableDatabase()).newSession();
}
/** * Query for writable DB */
protected static void openWritableDb() throws SQLiteException {
daoSession = new DaoMaster(getWritableDatabase()).newSession();
}
private static SQLiteDatabase getWritableDatabase() {
return mHelper.getWritableDatabase();
}
private static SQLiteDatabase getReadableDatabase() {
return mHelper.getReadableDatabase();
}
/** * 在applicaiton中初始化DatabaseHelper */
private static DaoMaster.DevOpenHelper getOpenHelper(@NonNull Context context, @Nullable String dataBaseName) {
closeDbConnections();//关闭数据库
return new DaoMaster.DevOpenHelper(context, dataBaseName, null);//初始化数据库
}
/**
* 只关闭helper就好,看源码就知道helper关闭的时候会关闭数据库
*/
public static void closeDbConnections() {
if (mHelper != null) {
mHelper.close();
mHelper = null;
}
if (daoSession != null) {
daoSession.clear();
daoSession = null;
}
}
@Override
public boolean insert(T t) {
try {
if (t == null)
return false;
openWritableDb();
getAbstractDao().insert(t);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean delete(T t) {
try {
if (t == null)
return false;
openWritableDb();
getAbstractDao().delete(t);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean deleteByKey(K k) {
try {
if (TextUtils.isEmpty(k.toString()))
return false;
openWritableDb();
getAbstractDao().deleteByKey(k);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean deleteList(List mList) {
try {
if (mList == null || mList.size() == 0)
return false;
openWritableDb();
getAbstractDao().deleteInTx(mList);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean deleteByKeyInTx(K... keys) {
try {
openWritableDb();
getAbstractDao().deleteByKeyInTx(keys);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean deleteAll() {
try {
openWritableDb();
getAbstractDao().deleteAll();
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean insertOrReplace(@NonNull T t) {
try {
if (t == null)
return false;
openWritableDb();
getAbstractDao().insertOrReplace(t);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean update(T t) {
try {
if (t == null)
return false;
openWritableDb();
getAbstractDao().update(t);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean updateInTx(T... t) {
try {
if (t == null)
return false;
openWritableDb();
getAbstractDao().updateInTx(t);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean updateList(List mList) {
try {
if (mList == null || mList.size() == 0)
return false;
openWritableDb();
getAbstractDao().updateInTx(mList);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public T selectByPrimaryKey(K key) {
try {
openReadableDb();
return getAbstractDao().load(key);
} catch (SQLiteException e) {
return null;
}
}
@Override
public List loadAll() {
openReadableDb();
return getAbstractDao().loadAll();
}
@Override
public boolean refresh(T t) {
try {
if (t == null)
return false;
openWritableDb();
getAbstractDao().refresh(t);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public void clearDaoSession() {
if (daoSession != null) {
daoSession.clear();
daoSession = null;
}
}
@Override
public boolean dropDatabase() {
try {
openWritableDb();
// DaoMaster.dropAllTables(database, true); // drops all tables
// mHelper.onCreate(database); // creates the tables
// daoSession.deleteAll(BankCardBean.class); // clear all elements
// from
// a table
} catch (Exception e) {
return false;
}
return true;
}
@Override
public void runInTx(Runnable runnable) {
try {
openWritableDb();
daoSession.runInTx(runnable);
} catch (SQLiteException e) {
}
}
@Override
public boolean insertList(List mList) {
try {
if (mList == null || mList.size() == 0)
return false;
openWritableDb();
getAbstractDao().insertInTx(mList);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public boolean insertOrReplaceList(List mList) {
try {
if (mList == null || mList.size() == 0)
return false;
openWritableDb();
getAbstractDao().insertOrReplaceInTx(mList);
} catch (SQLiteException e) {
return false;
}
return true;
}
@Override
public QueryBuilder getQueryBuilder() {
openReadableDb();
return getAbstractDao().queryBuilder();
}
@Override
public List queryRaw(String where, String... selectionArg) {
openReadableDb();
return getAbstractDao().queryRaw(where, selectionArg);
}
public Query queryRawCreate(String where, Object... selectionArg) {
openReadableDb();
return getAbstractDao().queryRawCreate(where, selectionArg);
}
public Query queryRawCreateListArgs(String where, Collection
在Application 内初始化 helper:
AbstractDatabaseManager.initOpenHelper(getApplicationContext());//初始化数据库
实体类:
@Entity(nameInDb = "NOTE")
public class Note {
@Id
private Long id;
@NotNull
private String text;
private String content;
private java.util.Date date;
@Generated(hash = 1272611929)
public Note() {
}
public Note(Long id) {
this.id = id;
}
@Generated(hash = 1657551704)
public Note(Long id, @NotNull String text, String content, java.util.Date date) {
this.id = id;
this.text = text;
this.content = content;
this.date = date;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@NotNull
public String getText() {
return text;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setText(@NotNull String text) {
this.text = text;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
}
实际类:
public class NoteDbManager extends AbstractDatabaseManager<Note,Long> {
@Override
public AbstractDao getAbstractDao() {
return daoSession.getNoteDao();
}
}
调用:
new NoteDbManager().insert(note);
new NoteDbManager().setDebug(true);
new NoteDbManager().delete(note);
public class BaseDao {
public static final String TAG = BaseDao.class.getSimpleName();
public static final boolean DUBUG = true;
public DaoManager manager;
public DaoSession daoSession;
public BaseDao(Context context) {
manager = DaoManager.getInstance();
manager.init(context);
daoSession = manager.getDaoSession();
manager.setDebug(DUBUG);
}
/**************************数据库插入操作***********************/
/**
* 插入单个对象
* @param object
* @return
*/
public boolean insertObject(T object){
boolean flag = false;
try {
flag = manager.getDaoSession().insert(object) != -1 ? true:false;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return flag;
}
/**
* 插入多个对象,并开启新的线程
* @param objects
* @return
*/
public boolean insertMultObject(final List objects){
boolean flag = false;
if (null == objects || objects.isEmpty()){
return false;
}
try {
manager.getDaoSession().runInTx(new Runnable() {
@Override
public void run() {
for (T object : objects) {
manager.getDaoSession().insertOrReplace(object);
}
}
});
flag = true;
} catch (Exception e) {
Log.e(TAG, e.toString());
flag = false;
}finally {
// manager.CloseDataBase();
}
return flag;
}
/**************************数据库更新操作***********************/
/**
* 以对象形式进行数据修改
* 其中必须要知道对象的主键ID
* @param object
* @return
*/
public void updateObject(T object){
if (null == object){
return ;
}
try {
manager.getDaoSession().update(object);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
/**
* 批量更新数据
* @param objects
* @return
*/
public void updateMultObject(final List objects, Class clss){
if (null == objects || objects.isEmpty()){
return;
}
try {
//反射
daoSession.getDao(clss).updateInTx(new Runnable() {
@Override
public void run() {
for(T object:objects){
daoSession.update(object);
}
}
});
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
/**************************数据库删除操作***********************/
/**
* 删除某个数据库表
* @param clss
* @return
*/
public boolean deleteAll(Class clss){
boolean flag = false;
try {
manager.getDaoSession().deleteAll(clss);
flag = true;
} catch (Exception e) {
Log.e(TAG, e.toString());
flag = false;
}
return flag;
}
/**
* 删除某个对象
* @param object
* @return
*/
public void deleteObject(T object){
try {
daoSession.delete(object);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
/**
* 异步批量删除数据
* @param objects
* @return
*/
public boolean deleteMultObject(final List objects, Class clss){
boolean flag = false;
if (null == objects || objects.isEmpty()){
return false;
}
try {
daoSession.getDao(clss).deleteInTx(new Runnable() {
@Override
public void run() {
for(T object:objects){
daoSession.delete(object);
}
}
});
flag = true;
} catch (Exception e) {
Log.e(TAG, e.toString());
flag = false;
}
return flag;
}
/**************************数据库查询操作***********************/
/**
* 获得某个表名
* @return
*/
public String getTablename(Class object){
return daoSession.getDao(object).getTablename();
}
/**
* 查询某个ID的对象是否存在
* @param
* @return
*/
public boolean isExitObject(long id,Class object){
QueryBuilder qb = (QueryBuilder) daoSession.getDao(object).queryBuilder();
qb.where(CustomerDao.Properties.Id.eq(id));
long length = qb.buildCount().count();
return length>0 ? true:false;
}
/**
* 根据主键ID来查询
* @param id
* @return
*/
public T QueryById(long id,Class object){
return (T) daoSession.getDao(object).loadByRowId(id);
}
/**
* 查询某条件下的对象
* @param object
* @return
*/
public List QueryObject(Class object,String where,String...params){
Object obj = null;
List objects = null;
try {
obj = daoSession.getDao(object);
if (null == obj){
return null;
}
objects = daoSession.getDao(object).queryRaw(where,params);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return objects;
}
/**
* 查询所有对象
* @param object
* @return
*/
public List QueryAll(Class object){
List objects = null;
try {
objects = (List) daoSession.getDao(object).loadAll();
} catch (Exception e) {
Log.e(TAG,e.toString());
}
return objects;
}
/***************************关闭数据库*************************/
/**
* 关闭数据库一般在Odestory中使用
*/
public void CloseDataBase(){
manager.closeDataBase();
}
public class NoteBase extends BaseDao<Note> {
public NoteBase(Context context) {
super(context);
}
@Override
public boolean insertObject(Note object) {
return super.insertObject(object);
}
}
/**
* Created by hzf on 2016/12/15 0015.
* 进行数据库的管理
* 1.创建数据库
* 2.创建数据库表
* 3.对数据库进行增删查改
* 4.对数据库进行升级
*/
public class DaoManager {
private static final String TAG = DaoManager.class.getSimpleName();
private static final String DB_NAME="note";//数据库名称
private volatile static DaoManager mDaoManager;//多线程访问
private static DaoMaster.DevOpenHelper mHelper;
private static DaoMaster mDaoMaster;
private static DaoSession mDaoSession;
private static SQLiteDatabase db;
private Context context;
/**
* 使用单例模式获得操作数据库的对象
* @return
*/
public static DaoManager getInstance(){
DaoManager instance = null;
if (mDaoManager==null){
synchronized (DaoManager.class){
if (instance==null){
instance = new DaoManager();
mDaoManager = instance;
}
}
}
return mDaoManager;
}
/**
* 初始化Context对象
* @param context
*/
public void init(Context context){
this.context = context;
}
/**
* 判断数据库是否存在,如果不存在则创建
* @return
*/
public DaoMaster getDaoMaster(){
if (null == mDaoMaster){
mHelper = new DaoMaster.DevOpenHelper(context,DB_NAME,null);
mDaoMaster = new DaoMaster(mHelper.getWritableDatabase());
}
return mDaoMaster;
}
/**
* 完成对数据库的增删查找
* @return
*/
public DaoSession getDaoSession(){
if (null == mDaoSession){
if (null == mDaoMaster){
mDaoMaster = getDaoMaster();
}
mDaoSession = mDaoMaster.newSession();
}
return mDaoSession;
}
/**
* 设置debug模式开启或关闭,默认关闭
* @param flag
*/
public void setDebug(boolean flag){
QueryBuilder.LOG_SQL = flag;
QueryBuilder.LOG_VALUES = flag;
}
/**
* 关闭数据库
*/
public void closeDataBase(){
closeHelper();
closeDaoSession();
}
public void closeDaoSession(){
if (null != mDaoSession){
mDaoSession.clear();
mDaoSession = null;
}
}
public void closeHelper(){
if (mHelper!=null){
mHelper.close();
mHelper = null;
}
}
}
new NoteBase(this).deleteObject(note);
new NoteBase(this).insertObject(note);
/**
* Created by hzf on 2016/12/14 0014.
* 单例模式适用场合
* 需要频繁的进行创建和销毁的对象;
* 创建对象时耗时过多或耗费资源过多,但又经常用到的对象;
* 工具类对象;
* 频繁访问数据库或文件的对象。
*/
public class GreenDaoManager {
private static GreenDaoManager mInstance;
private DaoMaster daoMaster;
private DaoSession daoSession;
private GreenDaoManager(){
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(BaseApplication.getContext(),Constants.DB_NAME,null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
daoSession = daoMaster.newSession();
}
//懒汉式(线程不安全)[不可用]
public static GreenDaoManager getInstance(){
if (mInstance == null) {
mInstance = new GreenDaoManager();
}
return mInstance;
}
//懒汉式,同步方法(不推荐)
public static synchronized GreenDaoManager getInstance4(){
if (mInstance == null) {
mInstance = new GreenDaoManager();
}
return mInstance;
}
//懒汉式,双重检查[推荐用]
public static GreenDaoManager getInstance2(){
if(mInstance == null){
synchronized (GreenDaoManager.class){
if(mInstance == null){
mInstance = new GreenDaoManager();
}
}
}
return mInstance;
}
//静态内部类[推荐用]
private static class GreenDaoManagerInstance {
private static final GreenDaoManager INSTANCE = new GreenDaoManager();
}
public static GreenDaoManager getInstance3(){
return GreenDaoManagerInstance.INSTANCE;
}
/**
* 判断数据库是否存在,如果不存在则创建
* @return
*/
// public DaoMaster getDaoMaster() {
// if(daoMaster == null) {
// helper = new DaoMaster.DevOpenHelper(BaseApplication.getContext(),Constants.DB_NAME,null);
// daoMaster = new DaoMaster(helper.getWritableDatabase());
// }
// return daoMaster;
// }
// /**
// * 完成对数据库的增删查找
// * @return
// */
public DaoSession getDaoSession() {
// if(daoSession == null){
// if(daoMaster == null){
// daoMaster = getDaoMaster();
// }
// daoSession = daoMaster.newSession();
// }
return daoSession;
}
public DaoSession getNewDaoSession(){
daoSession = daoMaster.newSession();
return daoSession;
}
/**
* 设置debug模式开启或关闭,默认关闭
* @param flag
*/
public void setDebug(boolean flag){
QueryBuilder.LOG_SQL = flag;
QueryBuilder.LOG_VALUES = flag;
}
/**
* 关闭数据库
*/
public void closeDataBase(){
closeHelper();
closeDaoSession();
}
public void closeDaoSession(){
if (null != daoSession){
daoSession.clear();
daoSession = null;
}
}
public void closeHelper(){
// if (helper!=null){
// helper.close();
// helper = null;
// }
}
}
GreenDaoManager.getInstance2().getDaoSession().getNoteDao().insert(note);
上面的三种写法只是对不同层进行的分装,主要思想还是直接将dao层接口抽离出来操作,让结构更加合理。
文章部分内容转自博客:http://blog.csdn.net/sinat_15877283/article/details/51098477