目录
一、简介
二、环境搭建
三、使用准备
四、简单使用示例
五、二次封装(重点)
六、GreenDao的常用注解
一、简介
- greenDAO 是一个将对象映射到 SQLite 数据库中的轻量且快速的 ORM 解决方案,GreenDao特点:
- 性能最大化,可能是Android平台上最快的ORM框架
- 易于使用的API
- 最小的内存开销
- 依赖体积小
- 支持数据库加密
- 强大的社区支持
- Github地址
https://github.com/greenrobot/greenDAO
二、环境搭建
- 在根目录的 build.gradle 添加
buildscript {
repositories {
jcenter()
// 添加仓库
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// 添加插件
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
}
- 在app的 build.gradle 添加
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // 应用插件
dependencies {
implementation 'org.greenrobot:greendao:3.2.2' // 添加依赖
}
- GreenDao 3 采用注解的方式来定义实体类,可按如下设置生成文件的目录,在app的 build.gradle 添加
greendao {
// 指定数据库schema版本号,迁移等操作会用到
schemaVersion 1
// 设置生成数据库文件的目录,默认是在build中,可以将生成的文件放到我们的java目录中
targetGenDir 'src/main/java'
// 设置生成的数据库相关文件的包名,默认为entity所在的包名
daoPackage 'com.shufeng.greendao.gen'
}
三、使用准备
参照 Android框架之路——GreenDao3.2.2的使用
- 编写实体类
package com.shufeng.greendaotest.bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.NotNull;
import org.greenrobot.greendao.annotation.Generated;
@Entity
public class Meizi
{
@Id(autoincrement = true)
private Long _id;
private String source;
@NotNull
private String url;
}
-
点击MakeProject后,就能看到实体类生成的代码及其他生成的文件
编写DaoManager
package com.shufeng.greendaotest.database;
import android.content.Context;
import com.shufeng.greendao.gen.DaoMaster;
import com.shufeng.greendao.gen.DaoSession;
import com.shufeng.greendaotest.BuildConfig;
import org.greenrobot.greendao.query.QueryBuilder;
/**
* 创建数据库、创建数据库表、包含增删改查的操作以及数据库的升级
* Created by Mr.sorrow on 2017/5/5.
*/
public class DaoManager
{
private static final String TAG = DaoManager.class.getSimpleName();
private static final String DB_NAME = "greendaotest";
private Context context;
//多线程中要被共享的使用volatile关键字修饰
private volatile static DaoManager manager = new DaoManager();
private static DaoMaster sDaoMaster;
private static DaoMaster.DevOpenHelper sHelper;
private static DaoSession sDaoSession;
/**
* 单例模式获得操作数据库对象
*
* @return
*/
public static DaoManager getInstance()
{
return manager;
}
private DaoManager()
{
setDebug();
}
public void init(Context context)
{
this.context = context;
}
/**
* 判断是否有存在数据库,如果没有则创建
*
* @return
*/
public DaoMaster getDaoMaster()
{
if (sDaoMaster == null)
{
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
sDaoMaster = new DaoMaster(helper.getWritableDatabase());
}
return sDaoMaster;
}
/**
* 完成对数据库的添加、删除、修改、查询操作,仅仅是一个接口
*
* @return
*/
public DaoSession getDaoSession()
{
if (sDaoSession == null)
{
if (sDaoMaster == null)
{
sDaoMaster = getDaoMaster();
}
sDaoSession = sDaoMaster.newSession();
}
return sDaoSession;
}
/**
* 打开输出日志,默认关闭
*/
public void setDebug()
{
if (BuildConfig.DEBUG)
{
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
}
/**
* 关闭所有的操作,数据库开启后,使用完毕要关闭
*/
public void closeConnection()
{
closeHelper();
closeDaoSession();
}
public void closeHelper()
{
if (sHelper != null)
{
sHelper.close();
sHelper = null;
}
}
public void closeDaoSession()
{
if (sDaoSession != null)
{
sDaoSession.clear();
sDaoSession = null;
}
}
}
- 编写Application,并初始化 DaoManager
package com.shufeng.greendaotest;
import android.app.Application;
import com.shufeng.greendaotest.database.DaoManager;
public class MyApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
initGreenDao();
}
private void initGreenDao()
{
DaoManager mManager = DaoManager.getInstance();
mManager.init(this);
}
}
注意在AndroidManifest.xml的application中添加
android:name=".MyApplication"
- 编写MeiziDaoUtils
package com.shufeng.greendaotest.database;
import android.content.Context;
import android.util.Log;
import com.shufeng.greendao.gen.MeiziDao;
import com.shufeng.greendaotest.bean.Meizi;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
public class MeiziDaoUtils
{
private static final String TAG = MeiziDaoUtils.class.getSimpleName();
private DaoManager mManager;
public MeiziDaoUtils(Context context){
mManager = DaoManager.getInstance();
mManager.init(context);
}
/**
* 完成meizi记录的插入,如果表未创建,先创建Meizi表
* @param meizi
* @return
*/
public boolean insertMeizi(Meizi meizi){
boolean flag = false;
flag = mManager.getDaoSession().getMeiziDao().insert(meizi) == -1 ? false : true;
Log.i(TAG, "insert Meizi :" + flag + "-->" + meizi.toString());
return flag;
}
/**
* 插入多条数据,在子线程操作
* @param meiziList
* @return
*/
public boolean insertMultMeizi(final List meiziList) {
boolean flag = false;
try {
mManager.getDaoSession().runInTx(new Runnable() {
@Override
public void run() {
for (Meizi meizi : meiziList) {
mManager.getDaoSession().insertOrReplace(meizi);
}
}
});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 修改一条数据
* @param meizi
* @return
*/
public boolean updateMeizi(Meizi meizi){
boolean flag = false;
try {
mManager.getDaoSession().update(meizi);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
/**
* 删除单条记录
* @param meizi
* @return
*/
public boolean deleteMeizi(Meizi meizi){
boolean flag = false;
try {
//按照id删除
mManager.getDaoSession().delete(meizi);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
/**
* 删除所有记录
* @return
*/
public boolean deleteAll(){
boolean flag = false;
try {
//按照id删除
mManager.getDaoSession().deleteAll(Meizi.class);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
/**
* 查询所有记录
* @return
*/
public List queryAllMeizi(){
return mManager.getDaoSession().loadAll(Meizi.class);
}
/**
* 根据主键id查询记录
* @param key
* @return
*/
public Meizi queryMeiziById(long key){
return mManager.getDaoSession().load(Meizi.class, key);
}
/**
* 使用native sql进行查询操作
*/
public List queryMeiziByNativeSql(String sql, String[] conditions){
return mManager.getDaoSession().queryRaw(Meizi.class, sql, conditions);
}
/**
* 使用queryBuilder进行查询
* @return
*/
public List queryMeiziByQueryBuilder(long id){
QueryBuilder queryBuilder = mManager.getDaoSession().queryBuilder(Meizi.class);
return queryBuilder.where(MeiziDao.Properties._id.eq(id)).list();
// return queryBuilder.where(MeiziDao.Properties._id.ge(id)).list();
}
}
四、简单使用示例
- 布局文件
- activity中使用
package com.shufeng.greendaotest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.shufeng.greendaotest.bean.Meizi;
import com.shufeng.greendaotest.database.MeiziDaoUtils;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private final String TAG = MainActivity.class.getSimpleName();
MeiziDaoUtils mMeiziDaoUtils;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_insert_one).setOnClickListener(this);
findViewById(R.id.btn_insert_many).setOnClickListener(this);
findViewById(R.id.btn_alter).setOnClickListener(this);
findViewById(R.id.btn_delete).setOnClickListener(this);
findViewById(R.id.btn_delete_all).setOnClickListener(this);
findViewById(R.id.btn_check_one).setOnClickListener(this);
findViewById(R.id.btn_check_all).setOnClickListener(this);
findViewById(R.id.btn_query_native_sql).setOnClickListener(this);
findViewById(R.id.btn_query_builder).setOnClickListener(this);
mMeiziDaoUtils = new MeiziDaoUtils(this);
}
@Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.btn_insert_one:
mMeiziDaoUtils.insertMeizi(new Meizi(null, "Google",
"http://7xi8d6.48096_n.jpg"));
break;
case R.id.btn_insert_many:
List meiziList = new ArrayList<>();
meiziList.add(new Meizi(null, "HuaWei",
"http://7xi8d648096_n.jpg"));
meiziList.add(new Meizi(null, "Apple",
"http://7xi8d648096_n.jpg"));
meiziList.add(new Meizi(null, "MIUI",
"http://7xi8d648096_n.jpg"));
mMeiziDaoUtils.insertMultMeizi(meiziList);
break;
case R.id.btn_alter:
Meizi meizi = new Meizi();
meizi.set_id(1l);
meizi.setSource("BAIDU");
meizi.setUrl("http://baidu.jpg");
mMeiziDaoUtils.updateMeizi(meizi);
break;
case R.id.btn_delete:
Meizi meizi1 = new Meizi();
meizi1.set_id(1002l);
mMeiziDaoUtils.deleteMeizi(meizi1);
break;
case R.id.btn_delete_all:
mMeiziDaoUtils.deleteAll();
break;
case R.id.btn_check_one:
Log.i(TAG, mMeiziDaoUtils.queryMeiziById(1002l).toString());
break;
case R.id.btn_check_all:
List meiziList1 = mMeiziDaoUtils.queryAllMeizi();
for (Meizi meizi2 : meiziList1) {
Log.i(TAG, meizi2.toString());
}
break;
case R.id.btn_query_native_sql:
String sql = "where _id > ?";
String[] condition = new String[]{"2"};
List meiziList2 = mMeiziDaoUtils.queryMeiziByNativeSql(sql, condition);
for (Meizi meizi2 : meiziList2) {
Log.i(TAG, meizi2.toString());
}
break;
case R.id.btn_query_builder:
List meiziList3 = mMeiziDaoUtils.queryMeiziByQueryBuilder(10);
for (Meizi meizi2 : meiziList3) {
Log.i(TAG, meizi2.toString());
}
break;
}
}
}
五、二次封装
如果实体类比较多,也即数据库表较多,但使用MeiziDaoUtils的方式编写,则会产生很多相似代码,因此编写了如下通用的DaoUtils
1、CommonDaoUtils
package com.shufeng.greendaotest.database;
import android.util.Log;
import com.shufeng.greendao.gen.DaoSession;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;
import java.util.List;
public class CommonDaoUtils
{
private static final String TAG = CommonDaoUtils.class.getSimpleName();
private DaoSession daoSession;
private Class entityClass;
private AbstractDao entityDao;
public CommonDaoUtils(Class pEntityClass, AbstractDao pEntityDao)
{
DaoManager mManager = DaoManager.getInstance();
daoSession = mManager.getDaoSession();
entityClass = pEntityClass;
entityDao = pEntityDao;
}
/**
* 插入记录,如果表未创建,先创建表
*
* @param pEntity
* @return
*/
public boolean insert(T pEntity)
{
boolean flag = entityDao.insert(pEntity) == -1 ? false : true;
Log.i(TAG, "insert Meizi :" + flag + "-->" + pEntity.toString());
return flag;
}
/**
* 插入多条数据,在子线程操作
*
* @param pEntityList
* @return
*/
public boolean insertMulti(final List pEntityList)
{
try
{
daoSession.runInTx(new Runnable()
{
@Override
public void run()
{
for (T meizi : pEntityList)
{
daoSession.insertOrReplace(meizi);
}
}
});
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
/**
* 修改一条数据
*
* @param pEntity
* @return
*/
public boolean update(T pEntity)
{
try
{
daoSession.update(pEntity);
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
/**
* 删除单条记录
*
* @param pEntity
* @return
*/
public boolean delete(T pEntity)
{
try
{
//按照id删除
daoSession.delete(pEntity);
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
/**
* 删除所有记录
*
* @return
*/
public boolean deleteAll()
{
try
{
//按照id删除
daoSession.deleteAll(entityClass);
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
/**
* 查询所有记录
*
* @return
*/
public List queryAll()
{
return daoSession.loadAll(entityClass);
}
/**
* 根据主键id查询记录
*
* @param key
* @return
*/
public T queryById(long key)
{
return daoSession.load(entityClass, key);
}
/**
* 使用native sql进行查询操作
*/
public List queryByNativeSql(String sql, String[] conditions)
{
return daoSession.queryRaw(entityClass, sql, conditions);
}
/**
* 使用queryBuilder进行查询
*
* @return
*/
public List queryByQueryBuilder(WhereCondition cond, WhereCondition... condMore)
{
QueryBuilder queryBuilder = daoSession.queryBuilder(entityClass);
return queryBuilder.where(cond, condMore).list();
}
}
2、DaoUtilsStore用来存放各个DaoUtils
package com.shufeng.greendaotest.database;
import com.shufeng.greendao.gen.HanziDao;
import com.shufeng.greendao.gen.MeiziDao;
import com.shufeng.greendaotest.bean.Hanzi;
import com.shufeng.greendaotest.bean.Meizi;
/**
* 存放DaoUtils
*/
public class DaoUtilsStore
{
private volatile static DaoUtilsStore instance = new DaoUtilsStore();
private CommonDaoUtils meiziDaoUtils;
private CommonDaoUtils hanziDaoUtils;
public static DaoUtilsStore getInstance()
{
return instance;
}
private DaoUtilsStore()
{
DaoManager mManager = DaoManager.getInstance();
MeiziDao _MeiziDao = mManager.getDaoSession().getMeiziDao();
meiziDaoUtils = new CommonDaoUtils(Meizi.class, _MeiziDao);
HanziDao _HanziDao = mManager.getDaoSession().getHanziDao();
hanziDaoUtils = new CommonDaoUtils(Hanzi.class, _HanziDao);
}
public CommonDaoUtils getMeiziDaoUtils()
{
return meiziDaoUtils;
}
public CommonDaoUtils getHanziDaoUtils()
{
return hanziDaoUtils;
}
}
3、使用
CommonDaoUtils meiziDaoUtils;
DaoUtilsStore _Store = DaoUtilsStore.getInstance();
meiziDaoUtils = _Store.getMeiziDaoUtils();
六、GreenDao的常用注解
实体@Entity注解
- schema:告知GreenDao当前实体属于哪个schema
- active:标记一个实体处于活跃状态,活动实体有更新、删除和刷新方法
- nameInDb:在数据库中使用的别名,默认使用的是实体的类名
- indexes:定义索引,可以跨越多个列
- createInDb:标记创建数据库表
基础属性注解
- @Id:主键 Long 型,可以通过@Id(autoincrement = true)设置自增长
- @Property:设置一个非默认关系映射所对应的列名,默认是使用字段名,例如:@Property(nameInDb = "name")
- @NotNull:设置数据库表当前列不能为空
- @Transient:添加此标记后不会生成数据库表的列
索引注解
- @Index:使用@Index作为一个属性来创建一个索引,通过name设置索引别名,也可以通过unique给索引添加约束
- @Unique:向数据库添加了一个唯一的约束
关系注解
- @ToOne:定义与另一个实体(一个实体对象)的关系
- @ToMany:定义与多个实体对象的关系