GreenDao的基本使用(android数据库)

阅读 779
收藏 39
2017-11-02
原文链接:blog.csdn.net

在android中,在有些数据量相对较大或者处于安全考虑的情况下,会使用android自带的数据库—-sqlite: 但是使用sqlite需要考虑到以下几点:

    1.严格控制数据库资源的打开与关闭(db,cursor);
    2.在遍历数据时候取到的是cursor要转化为list再使用
    3.事务回滚,可以大大优化数据库的效率;

在android开发中我们会遇到一些数据库,内部框架做了封装使用起来比较方便:如 ormLite greenDao等

相比而言,greendao应该是最快,效率最高的数据库框架(greendao官网有介绍),ok直接代码详解greemdao.进入正题:

1.greenDao框架的初始化(准备工作与接入)

1.1

//首先实在project的build中配置:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        //greenDao的配置
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'


    }
}

1.2

//在moudle的build中配置

apply plugin: 'com.android.application'

//greenDao依赖
apply plugin: 'org.greenrobot.greendao'

android {

    ........

    //在创建玩实体类之后make project 存放greenDao  DB 的包位置
    greendao {
        schemaVersion 1
        daoPackage 'com.example.mysmall.greendao.greendao'//这个是生成代码保存的包名
        targetGenDir 'src/main/java'//保存到java代码路径
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    .....
    //greenDao的配置
    compile 'org.greenrobot:greendao:3.2.2'
    compile 'org.greenrobot:greendao-generator:3.2.2'
}

2.创建实体类 接着点击 Build -> Make Project

创建实体类: @Generated(hash = 664611791)中的hash参数 是build->Make Project之后生成的:

@Entity
public class User {

    /**定义主键*/
    @Id(autoincrement = true)
    private long id;


    private String name;
    private int age;
    private String sex;


    @Generated(hash = 664611791)
    public User(long id, String name, int age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }


    @Generated(hash = 586692638)
    public User() {
    }


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }


    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

需要注意一下 上面实体类通过注解会映射为数据库表(就不需要自己去写数据库创建的sal);
ok~下面来看注解:
@Entity表明该类是持久化的类(持久化含义,存入数据库文件中,作本地化处理)
@Id选择一个long或Long类型的属性作为该实体所对应数据库中数据表的主键(注意数据类型必须是long)
@Generated写在构造方法前

然后是关键性的一步build->Make Project然后自动生成数据库的操作类:
这里写图片描述
就是DaoMaster DaoSession UserDao;

3数据库操作类生成 开始用greenDao操作数据库:(用log来展示每次操作的数据变化):

3.1数据库的初始化 在 App(extends Application中实现代码):

public class App extends Application{


    private UserDao userDao;
    private static App mApp;

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

        /**初始化数据库*/
        DaoMaster.DevOpenHelper mHelper = new DaoMaster.
        DevOpenHelper(this, "user-db", null);

        SQLiteDatabase db = mHelper.getWritableDatabase();
        DaoMaster master = new DaoMaster(db);
        DaoSession daoSession = master.newSession();
        userDao = daoSession.getUserDao();

    }


    public static App getInstance(){
        if (mApp == null){
            synchronized (App.class){
                mApp = new App();
            }
        }


        return mApp;
    }

    public UserDao getDao(){
        return userDao;
    }
}

核心代码:

 DaoMaster.DevOpenHelper mHelper = new DaoMaster.
        DevOpenHelper(this, "user-db", null);

        SQLiteDatabase db = mHelper.getWritableDatabase();
        DaoMaster master = new DaoMaster(db);
        DaoSession daoSession = master.newSession();
        userDao = daoSession.getUserDao();

3.2数据库的增删改查:

    private void initDelete() {
        //mDao.deleteByKey(Long.valueOf(1));
        String trim = mPos.getText().toString().trim();
        if (trim != null && !trim.equals("")) {
            mDao.deleteByKey(Long.valueOf(trim));


            QueryBuilder<User> qb = mDao.queryBuilder();
            List<User> list = qb.where(UserDao.Properties.Id.eq(Long.valueOf(trim))).list();
            if (list.size()<1){
                Toast.makeText(this,"指定数据删除成功",Toast.LENGTH_SHORT).show();
            }

        }else {
            mDao.deleteAll();
        }

    }

    private void initUpdate() {

        String trim = mPos.getText().toString().trim();
        if (trim != null && !trim.equals("")) {
            User user = mDao.load(Long.valueOf(trim));
            user.setName("保尔柯察金");
            mDao.update(user);

        }




    }

    private void initInsert() {
        for (int i = 0; i < 5; i++) {
            mIndex ++;
            if (isEcho(String.valueOf(mIndex))){
                Toast.makeText(this,"主键重复",Toast.LENGTH_SHORT).show();
            }else {
                User user = new User(Long.valueOf(mIndex), "张三" + i, 18, "男");
                mDao.insert(user);
            }

        }


    }

    private void initSelect() {
        Query<User> query = mDao.queryBuilder().orderAsc(UserDao.Properties.Id).build();
        List<User> list = query.list();
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            String s = user.toString();
            Log.i("query",s);
        }
    }


    /**判断主键是否重复*/
    private boolean isEcho(String id){
        QueryBuilder<User> qb = mDao.queryBuilder();
        List<User> list = qb.where(UserDao.Properties.Id.eq(id)).list();
        if (list.size() > 0){
            return true;
        }
        return false;

    }

ok~ 从上面代码中可以看到 没有依据sql的操作语句 而且 每次操作完成资源是自动开关,不需要你手动开关数据库/游标/事务

是不是很方便呢;

4完整代码展示 :

下面粘贴完整代码:

这里写图片描述

//app

package com.example.mysmall.greendao.global;

import android.app.Application;
import android.database.sqlite.SQLiteDatabase;

import com.example.mysmall.greendao.greendao.DaoMaster;
import com.example.mysmall.greendao.greendao.DaoSession;
import com.example.mysmall.greendao.greendao.UserDao;

/**
 * Created by houruixiang on 2017/10/31.
 */

public class App extends Application{


    private UserDao userDao;
    private static App mApp;

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

        /**初始化数据库*/
        DaoMaster.DevOpenHelper mHelper = new DaoMaster.DevOpenHelper(this, "user-db", null);
        SQLiteDatabase db = mHelper.getWritableDatabase();
        DaoMaster master = new DaoMaster(db);
        DaoSession daoSession = master.newSession();
        userDao = daoSession.getUserDao();

    }


    public static App getInstance(){
        if (mApp == null){
            synchronized (App.class){
                mApp = new App();
            }
        }


        return mApp;
    }

    public UserDao getDao(){
        return userDao;
    }
}

//MainActivity

package com.example.mysmall.greendao;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mysmall.greendao.global.App;
import com.example.mysmall.greendao.greendao.UserDao;
import com.example.mysmall.greendao.model.User;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mSelect;
    private Button mInsert;
    private Button mUpdate;
    private Button mDelete;
    private int mIndex;
    private UserDao mDao;
    private EditText mPos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**获取数据库操作对象*/
        mDao = ((App) getApplication()).getDao();


        initView();
    }




    private void initView() {
        mSelect = (Button) findViewById(R.id.seclet);
        mInsert = (Button) findViewById(R.id.insert);
        mUpdate = (Button) findViewById(R.id.update);
        mDelete = (Button) findViewById(R.id.delete);
        mPos = (EditText) findViewById(R.id.tarPosition);


        mSelect.setOnClickListener(this);
        mInsert.setOnClickListener(this);
        mUpdate.setOnClickListener(this);
        mDelete.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.seclet:
                initSelect();
                break;
            case R.id.insert:
                initInsert();
                break;
            case R.id.update:
                initUpdate();
                break;
            case R.id.delete:
                initDelete();
                break;

        }

    }

    private void initDelete() {
        //mDao.deleteByKey(Long.valueOf(1));
        String trim = mPos.getText().toString().trim();
        if (trim != null && !trim.equals("")) {
            mDao.deleteByKey(Long.valueOf(trim));


            QueryBuilder<User> qb = mDao.queryBuilder();
            List<User> list = qb.where(UserDao.Properties.Id.eq(Long.valueOf(trim))).list();
            if (list.size()<1){
                Toast.makeText(this,"指定数据删除成功",Toast.LENGTH_SHORT).show();
            }

        }else {
            mDao.deleteAll();
        }

    }

    private void initUpdate() {

        String trim = mPos.getText().toString().trim();
        if (trim != null && !trim.equals("")) {
            User user = mDao.load(Long.valueOf(trim));
            user.setName("保尔柯察金");
            mDao.update(user);

        }




    }

    private void initInsert() {
        for (int i = 0; i < 5; i++) {
            mIndex ++;
            if (isEcho(String.valueOf(mIndex))){
                Toast.makeText(this,"主键重复",Toast.LENGTH_SHORT).show();
            }else {
                User user = new User(Long.valueOf(mIndex), "张三" + i, 18, "男");
                mDao.insert(user);
            }

        }


    }

    private void initSelect() {
        Query<User> query = mDao.queryBuilder().orderAsc(UserDao.Properties.Id).build();
        List<User> list = query.list();
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            String s = user.toString();
            Log.i("query",s);
        }
    }


    /**判断主键是否重复*/
    private boolean isEcho(String id){
        QueryBuilder<User> qb = mDao.queryBuilder();
        List<User> list = qb.where(UserDao.Properties.Id.eq(id)).list();
        if (list.size() > 0){
            return true;
        }
        return false;

    }
}

总而言之 greendao的框架作为android的数据库框架会很大程度提高效率;有兴趣的可以探讨其内部实现原理机制~感谢阅读 天气转冷 小心感冒哦

评论