GreenDao笔记

GreenDao讲解

1.复习SQL语句(结构化查询语言)

1.SQL语句分类

DDL数据定义语言
DML数据操作语言
DCL数据控制语言
DQL数据查询语言

2.SQL语句

1)库
	create database aaa; //创建数据库
	
	drop database aaa;   //删除数据库
	
	use aaa; 			//切换使用数据库
	
	show databases;		//显示数据库

2)表
	create table abc(		//创建表结构
		name text,
		sex varchar(100),
		age int(10)
	);
	
	drop table abc;		//删除表
	
	desc abc;			//显示表结构
	
3)数据
	insert into abc(name,sex,age) values('abc','nan',20);	//插入数据
		
	update abc set age = 101 【where name = 'abc'】			//更改数据
	
	delete from abc 【where name = 'abc'】					//删除数据
	
	select * from abc 【where age > 18】						//查询数据
	
4)约束
	主键:	primary key
	自增: 	auto_increment
	非空:  not null
	唯一:  unique
	
	create table abc(
		id	int(100) primary key auto_increment,    主键自增
		name varchar(100) not null unique,			非空唯一
		sex varchar(100),
		age int(10)
	);

5)查询
一、基本查询
	select * from emp;
	
	select empno,ename,sal from emp;
	
	select distinct deptno from emp;
	
	select sal*1.5 from emp;
	select concat('$',sal) from emp;
	select concat(sal,'RMB') from emp;
	select ifnull(comm,0)+1000 from emp;
	select sal as 奖金 from emp;

二、条件查询
	select * from emp where deptno = 20;
	select * from emp where deptno != 20;
	select * from emp where sal >=20000;
	select * from emp where sal >=10000 and sal <=20000;
	select * from emp where sal<=10000 or sal >=40000;
	select * from emp where comm is null;
	select * from emp where comm is not null;
	select * from emp where sal between 20000 and 40000;
	select * from emp where deptno in(10,30);

三、模糊查询   _某一个字符    %多个字符
	select * from emp where ename like '张_';
	select * from emp where ename like '张%';
	select * from emp where ename like '_一_';

四、排序
	select * from emp order by sal asc;
	select * from emp order by sal desc;

五、聚合函数
	select max(sal) from emp;
	select min(sal) from emp;
	select count(ename) from emp;
	select sum(sal) from emp;
	select avg(sal) from emp;

六、分组
	select deptno,count(ename) from emp group by deptno;


总结:
	select deptno,count(ename)
	from emp
	where sal >= 10000
	group by deptno
	order by deptno asc;

2.复习SQLliteDatabase

SQLiteDatabase的创建和实现的方法                                          
SQLiteOpenHelper的使用                                         
onCreate的调用机制,onUpgrade的调用机制;建库、建表                                             
增删改查(使用sql语句方式)
增删改查(使用系统方法)

3.GreenDao的概述以及特点

基于对象关系的映射方式来操作数据库的框架,提供一个接口通过操作对象的方式操作数据库

适用于 Android 的ORM 框架,现在市面上主流的框架有 OrmLite、SugarORM、Active Android、Realm 与 GreenDAO。

GreenDAO是一种Android数据库ORM(对象映射关系(Object Relation Mapping))框架,与OrmLite、ActiveOrm、LitePal等数据库相比,单位时间内可以插入、更新和查询更多的数据,而且提供了大量的灵活通用接口。

1,通常我们在使用GreenDao的时候,我们只需定义数据模型,GreenDao框架将创建数据对象(实体)和DAO(数据访问对象),能够节省部分代码。
2,不向性能妥协,使用了GreenDao,大多数实体可以以每秒几千个实体的速率进行插入,更新和加载。
3,GreenDao支持加密数据库来保护敏感数据。
4,微小的依赖库,GreenDao的关键依赖库大小不超过100kb.
5,如果需要,实体是可以被激活的。而活动实体可以透明的解析关系(我们要做的只是调用getter即可),并且有更新、删除和刷新方法,以便访问持久性功能。
6,GreenDao允许您将协议缓冲区(protobuf)对象直接保存到数据库中。如果您通过protobuf通话到您的服务器,则不需要另一个映射。常规实体的所有持久性操作都可以用于protobuf对象。所以,相信这是GreenDao的独特之处。
7,自动生成代码,我们无需关注实体类以及Dao,因为GreenDao已经帮我们生成了。
8,开源 有兴趣的同学可以查看源码,深入去了解机制。

4.GreenDao配置依赖

官网:
	https://github.com/greenrobot/greenDAO/

配置:
	//1.工程配置:添加插件 更好支持GreenDao
	buildscript {
	    repositories {
	        jcenter()
	        mavenCentral() // 添加的代码
	    }
	    dependencies {
	        classpath 'com.android.tools.build:gradle:2.3.3'
	        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
	    }
	}

	//2.项目配置:添加插件
	apply plugin: 'com.android.application'
	apply plugin: 'org.greenrobot.greendao' // apply plugin
	
	//3.项目配置:添加依赖
	dependencies {
	    //greendao
    	implementation 'org.greenrobot:greendao:3.2.2' // add library
	}

	//4.初始化GreenDao配置
	greendao{
        schemaVersion 1 //数据库版本号
        daoPackage 'com.example.lizhengjun.dao'  //数据库全路径
        targetGenDir 'src/main/java'  //存放位置
    }

	schemaVersion--> 指定数据库schema版本号,迁移等操作会用到;
	daoPackage --> dao的包名,包名默认是entity所在的包;
	targetGenDir --> 生成数据库文件的目录;

5.GreenDao的使用思路

//1、配置文件中的设置
// 在根工程中完成内容配置:
buildscript {
    repositories {
        jcenter()
        mavenCentral() // 添加的代码
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
    }
}
 
//在子工程中完成内容配置:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
 
dependencies {
    compile 'org.greenrobot:greendao:3.2.2' // add library
}


2、设置Green中的DaoMaster/DaoSession/实体类Dao生成路径
//自定义生成路径 daoPackage 'a.b.c'
greendao {
    schemaVersion 1
    daoPackage 'com.example.lizhengjun.dao'
    targetGenDir 'src/main/java'
}


3、设置实体类
@Entity
public class Student {

    @Id(autoincrement = true)
    private Long id;

    @Property
    @NotNull
    private String name;

    @Property
    private int age;
}

4、文件生成
Build - > ReBuild Project

5、在Application类中完成内容配置(或者使用工具类)

Application有自己的生命周期,OnCreate方法必须首先被调用
①本类对象的获取
②DaoMaster、DaoSession对象的获取
③提供方法,获取DaoSession对象

需要注意:必须在AndroidManifest.xml文件完成配置
<application
        android:name=".App">
</application>

6、获取实体类Dao对象
XXXDao xxxdao =  App.getInstance().getDaoSession().getXXXDao();
xxxdao.增删改查();

6.GreenDao注解

@Entity   标识实体类,greenDAO会映射成sqlite的一个表,表名为实体类名的大写形式
@Id 标识主键,该字段的类型为long或Long类型,autoincrement设置是否自动增长
@Property       标识该属性在表中对应的列名称, nameInDb设置名称
@Transient      标识该属性将不会映射到表中,也就是没有这列
@NotNull         设置表中当前列的值不可为空
@Convert         指定自定义类型(@linkPropertyConverter)
@Generated 运行所产生的构造函数或者方法,被此标注的代码可以变更或者下次运行时清除
@Index    使用@Index作为一个属性来创建一个索引;
@JoinEntity     定义表连接关系
@JoinProperty         定义名称和引用名称属性关系
@Keep     注解的代码段在GreenDao下次运行时保持不变
@OrderBy        指定排序方式
@ToMany         定义与多个实体对象的关系
@ToOne  定义与另一个实体(一个实体对象)的关系
@Unique 向数据库列添加了一个唯一的约束

/**
 * @Entity
 * @Id(autoincrement = true)  标志主键
 * @NotNull 标志这个字段不能是null
 * @Property(nameInDb = "User")
 * @Transient 表示不存储在数据库中
 * @Index(unique = true)
 * @Unique 用于标志列的值的唯一性。
 */

7.GreenDao对外提供的核心类简介

1,DaoMaster
DaoMaster保存数据库对象(SQLiteDatabase)并管理特定模式的Dao类。它具有静态方法来创建表或将他们删除。其内部类OpenHelper和DevOpenHelper是在SQLite数据库中创建模式的SQLiteOpenHelper实现。

2,DaoSession
管理特定模式的所有可用Dao对象,您可以使用其中一个getter方法获取。DaoSession还为实体提供了一些通用的持久性方法,如插入,加载,更新,刷新和删除。最后,DaoSession对象也跟踪一个身份范围。

3,Dao层
数据访问对象(Dao)持续存在并查询实体。对于每个实体,GreenDao生成一个Dao,它比DaoSession有更多的持久化方法,例如:count,loadAll和insertInTx。

4,实体
持久对象,通常实体是使用标准Java属性(如POJO或JavaBean)来表示数据库的对象。



1、DevOpenHelper:创建SQLite数据库的SQLiteOpenHelper的具体实现。 
2、DaoMaster:GreenDao的顶级对象,作为数据库对象、用于创建表和删除表。 
3、DaoSession:管理所有的Dao对象,Dao对象中存在着增删改查等API。

8.GreenDao使用

1.核心使用步骤

//1.创建数据库
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MyApp.getMyApp(), "student.db");

//2.获取读写对象
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());

//3.获取管理器类
DaoSession daoSession = daoMaster.newSession();

//4.获取表对象
 studentDao = daoSession.getStudentDao();


daoSession.clear();  清除整个session,没有缓存对象返回

2.完整使用步骤(Application)

public class App extends Application {

    private StudentDao studentDao;//Dao操作类

    private static App app;

    public static App getInstance() {
        return app;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //本类对象
        app = this;

        //创建数据库以及创建数据表
        createDataBase();
    }

    private void createDataBase() {
        //1.创建数据库
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "student.db");

		//2.获取读写对象
        DaoMaster daoMaster = new DaoMaster(helper.getWritableDatabase());
		
		//3.获取管理器类
        DaoSession daoSession = daoMaster.newSession();

		//4.获取表对象
        studentDao = daoSession.getStudentDao();
    }

    public StudentDao getStudentDao() {
        return studentDao;
    }
}

2.完整使用步骤(工具类)

public class MyApp extends Application {

    private static MyApp myApp;

    @Override
    public void onCreate() {
        super.onCreate();	

        myApp = this;
    }

    public static MyApp getMyApp() {
        return myApp;
    }
}

<application
    android:name=".MyApp"
    ...>
    
</application>

public class MyDatabaseHelper {

    public StudentDao studentDao;//Dao操作类

    private static MyDatabaseHelper myDatabaseHelper;

    //创建生成数据库
    private MyDatabaseHelper(){

        //1.创建数据库
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MyApp.getMyApp(), "student.db");

        //2.获取读写对象
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());

        //3.获取管理器类
        DaoSession daoSession = daoMaster.newSession();

        //4.获取表对象
         studentDao = daoSession.getStudentDao();
    }

    public static MyDatabaseHelper getMyDatabaseHelper() {
        if(myDatabaseHelper == null){
            synchronized (MyDatabaseHelper.class){
                if (myDatabaseHelper ==null){
                    myDatabaseHelper = new MyDatabaseHelper();
                }
            }
        }
        return myDatabaseHelper;
    }

	。。。增删改查操作。。。
}

8.GreenDao的增删改查

1、增		insert
2、删		deleteByKey
3、改		update
4、查		loadAll


//插入
public void insertAll(List<Student> list){
    studentDao.insertInTx(list);
}

public void insert(Student student){
    studentDao.insert(student);
}

public void insert(Student student){
    studentDao.insertOrReplace(student);
}

//删除
public void deleteAll(){
    studentDao.deleteAll();
}

public void delete(Student student){
    studentDao.delete(student);
}


//更改
public void updateAll(List<Student> list){
    studentDao.updateInTx(list);
}

public void update(Student student){
    studentDao.update(student);
}

//查询
public List<Student> queryAll(){
    return  studentDao.queryBuilder().list();
}
public List<Student> queryStudent(Student student){
    return  studentDao.queryBuilder().where(StudentDao.Properties.Name.eq(student.getName())).list();
}
public List<Student> queryStudent2(Student student){
    return  studentDao.queryBuilder().where(StudentDao.Properties.Name.eq(student.getName()),StudentDao.Properties.Age.gt(student.getAge())).list();
}
public List<Student> queryPage(int page,int count){
    return  studentDao.queryBuilder().offset(page*count).limit(count).list();
}

public StudentDao query(PersonInfor studentDao){
	StudentDao oldStudentDao = studentDao.queryBuilder().where(StudentDao.Properties.Id.eq(studentDao.getId())).build().unique();
    return oldStudentDao;
}

9.GreenDao数据库升级

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值