GreenDao3.2.2集成和基本使用

官方git网址:(https://github.com/greenrobot/greenDAO)

  • 优点:一个精简的库;性能最大化;最小的内存开销;易于使用的 APIs;支持数据库加密;依赖体积小;强大的社区支持。

集成方式

  1. 在项目的根build.gradle文件里:
buildscript {
    repositories {
        jcenter()
        mavenCentral() // add repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
    }
}

2.在项目app的build.gradle文件里:

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin 

android {
    ...
}

greendao {
    schemaVersion 1 // 数据库版本号
    daoPackage '如:包名.greendao' //greenDao 自动生成的代码保存的包名
    targetGenDir 'src/main/java' //自动生成的代码存储的路径,默认是 build/generated/source/greendao.
//    generateTests false //true的时候自动生成测试单元
//    targetGenDirTests: 测试单元的生成目录默认是 src/androidTest/java
}


dependencies {
    implementation 'org.greenrobot:greendao:3.2.2' // add library
}

3.创建数据库实体类Bean:

@Entity
public class UserInfo {
    @Id
    private Long id;
    private String name;
    private int age;
    @Generated(hash = 577950320)
    public UserInfo(Long id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    @Generated(hash = 1279772520)
    public UserInfo() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return this.age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

注意:实体类文件只需要写好变量名,get和set方法是build后自动生成的

  • 实体@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:定义与多个实体对象的关系
  1. 编写还实体类后,点击Build->Make Project,Build完成后 ,会在之前配置的 greenDao 自动生成的代码的指定目录下生成以下三个文件
  • DaoMaster
  • DaoSession
  • UserInfoDao

初始化GreenDao

一般建议在Application中初始化数据库

public class MyAplication extends Application {
	private static APPAplication context;
	public static APPAplication getApplication(){
		return context;
	}

	private DaoMaster.DevOpenHelper mHelper;
	private SQLiteDatabase db;
	private DaoMaster mDaoMaster;
	private DaoSession mDaoSession;
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		context=this;
	
		setDataBase();
	}

	private static final String DATA_BASE_NAME="test-db";
	private void setDataBase() {
		mHelper=new DaoMaster.DevOpenHelper(this,DATA_BASE_NAME,null);
		db=mHelper.getWritableDatabase();
		mDaoMaster=new DaoMaster(db);
		mDaoSession=mDaoMaster.newSession();
	}

	public DaoSession getDaoSession(){
		return mDaoSession;
	}
	public SQLiteDatabase getDb(){
		return db;
	}

}

UserInfoDao infoDao=MyAplication.getApplication().getDaoSession().getUserInfoDao();
        //add
        for (int i=0;i<10;i++){
            if (infoDao.queryBuilder().where(UserInfoDao.Properties.Name.eq("小米"+i)).unique()==null){
            //判断名字是否已存在
                UserInfo userInfo1=new UserInfo(null,"小米"+i,(i*2));
                infoDao.insert(userInfo1);
            }

        }

  • deleteBykey(Long key) :根据主键删除一条记录。
  • delete(UserInfo entity) :根据实体类删除一条记录,一般结合查询方法,查询出一条记录之后删除。
  • deleteAll(): 删除所有记录
UserInfoDao infoDao=MyAplication.getApplication().getDaoSession().getUserInfoDao();

infoDao.deleteByKey(1L);//通过Long型ID删除数据

  • update(UserInfo entity):更新一条记录
UserInfoDao infoDao=MyAplication.getApplication().getDaoSession().getUserInfoDao();

infoDao.update(new UserInfo(1L,"小名",20));

  • loadAll():查询所有记录
  • load(Long key):根据主键查询一条记录
  • queryBuilder().list():返回:List
  • queryBuilder().where(UserDao.Properties.Name.eq("")).list():返回:List
  • queryRaw(String where,String selectionArg):返回:List
UserInfoDao infoDao=MyAplication.getApplication().getDaoSession().getUserInfoDao();

//查询姓名为:‘小米5’的数据
List<UserInfo> list=infoDao.queryBuilder().where(UserInfoDao.Properties.Name.eq("小米5")).build().list();

缓存问题

  • 当修改更新某一条数据后,重新查询会发现查找出来的数据依然是未修改前的数据,这是因为Greendao到数据查询是带缓存的查询,你搜索过的数据会生成缓存,查询的时候会先查询缓存,这样可以节约资源,提高效率,但是也由此产生一些问题,所以此时需要先清除缓存,在做查询操作。
    可以通过以下代码清除缓存 后再做查询操作
//清除所有数据库缓存
daoSession.clear()
//MyAplication.getApplication().getDaoSession().clear();


//清空指定某个数据表缓存
//MyAplication.getApplication().getDaoSession().getUserInfoDao().detachAll();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值