greenDao基本使用步骤

greenDao基本使用步骤


  • API文档 链接

  • 第一步:接入jar包
  1. app的build.gradle中

dependencies 的节点下添加依赖

compile 'org.greenrobot:greendao:3.2.2'
compile 'org.greenrobot:greendao-generator:3.2.2'
  1. 在project的build.gradle中

buildscript 下的 dependencies中添加

 classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

allprojects 下的 repositories 中添加

mavenCentral() // add repository
  1. 新建的AndroidLib库中

lib 的build.gradle 中最上面添加:

apply plugin: 'org.greenrobot.greendao'

在android节点下添加:greendao配置文件

greendao {
        schemaVersion 2
        daoPackage 'com.mrko.dao'
        targetGenDir 'src/main/java'
    }

dependencies 节点下添加:greenDao依赖

compile 'org.greenrobot:greendao:3.2.2'
compile 'org.greenrobot:greendao-generator:3.2.2'
  1. 将新建的AndroidLib库依赖到APP项目中、

  • 第二步:新建AndroidLib。实现封装Utils

只有建立完成之后才能去进行build.gradle配置(也就是第一步的3.4点)

  1. 新建一个module-->选择Android jar。
  2. 进行第一步中的序号3进行gradle的配置。
  3. 新建一个DBApplication。代码如下

DBApplication这继承的是app的Application
本身AndroidManifest.xml不做处理

package com.mrko;
import android.app.Application;
import com.mrko.dao.DaoMaster;
import com.mrko.dao.DaoSession;
import org.greenrobot.greendao.database.Database;

/**
 * Created by Mrko on 2017/9/19-10:16.
 * Email:[email protected]
 */

public class DBApplication extends Application {
    //定义数据库名称
    public static final String DB_NAME = "Stuent.db";
    private DaoSession session;
    //获取本地的一个实例
    private static DBApplication DBApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        DBApplication = this;
        initDB();
    }

    /**
     * 初始化
     * 1.先获取DexOpenHelper的实例。新建一个数据库表
     * 2.获取dataBase的写入权限
     * 3.新建一个DaoMaster类。将dataBase交给其管理
     * 4.获取到Session的实例(session就是操作数据库的直接类)
     */
    public void initDB() {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, DB_NAME);
        Database database = devOpenHelper.getWritableDb();
        DaoMaster daoMaster = new DaoMaster(database);
        session = daoMaster.newSession();
    }

    public static DBApplication getAPPlication() {
        return DBApplication;
    }

    public synchronized DaoSession getDaoSession() {
        if (session == null) {
            initDB();
        }
        return session;
    }
}


  • 第三步:新建实体类、也就是数据库表中所需要字段。

Student 类。

  1. 开始新建时候代码如下:
package com.mrko.mydb;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;

/**
 * Created by Mrko on 2017/9/19-10:00.
 * Email:[email protected]
 */

@Entity
public class Student {
    //注意 是Long 不是long 
    @Id(autoincrement = true)
    private Long id;

    @Property(nameInDb = "name")
    private String name;

    @Property(nameInDb = "age")
    private int age;

    
}

  1. 然后在Make project (点击小锤子)
  2. 新生成代码如下:并会在build.gradle中配置的地址(targetGenDir 'src/main/java')的目录下生成三个实体类(DaoMaster、DaoSession、StudentDao)(一般添加新的字段。可以把之前生成的三个实体类删除,重新生成)
package com.mrko.mydb;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.Generated;

/**
 * Created by Mrko on 2017/9/19-10:00.
 * Email:[email protected]
 */

@Entity
public class Student {
    //注意 是Long 不是long
    @Id(autoincrement = true)
    private Long id;

    @Property(nameInDb = "name")
    private String name;

    @Property(nameInDb = "age")
    private int age;

    @Generated(hash = 352757281)
    public Student(Long id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Generated(hash = 1556870573)
    public Student() {
    }

    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;
    }

    
    
}

  • 第四步:新建数据库工具类

    DBUtils 数据库统一管理实现封装

package com.mrko.helper;

import android.util.Log;

import com.mrko.DBApplication;
import com.mrko.dao.DaoSession;
import com.mrko.dao.StudentDao;
import com.mrko.mydb.Student;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * Created by Mrko on 2017/9/19-10:35.
 * Email:[email protected]
 */

public class DBStudentUtils {
    private static DaoSession mDaoSession;
    private static StudentDao mStuentDao;
    private static DBStudentUtils instance = null;

    private DBStudentUtils() {

    }

    /**
     * 双重校验锁单例模式
     * 实例化Session和Dao类
     * @return
     */
    public static DBStudentUtils getInstance() {
        if (instance == null) {
            synchronized (DBStudentUtils.class) {
                if (instance == null) {
                    instance = new DBStudentUtils();
                }
                mDaoSession = DBApplication.getAPPlication().getDaoSession();
                mStuentDao = mDaoSession.getStudentDao();
            }
        }
        return instance;
    }

    public Student makeStudent(String name, int age) {
        Student student = null;
        if (student == null) {
            student = new Student();
            Log.e(TAG, "makeStudent: " + student.getId());
            student.setName(name);
            student.setAge(age);
            insertStudent(student);
        }
        return student;
    }

    public void insertStudent(Student student) {
        mStuentDao.insert(student);
    }

    public void updateStudent(Student student) {
        mStuentDao.update(student);
    }

    public void deleteStudent(Long id) {
        mStuentDao.deleteByKey(id);
    }

    public List queryStudent(int age) {
        QueryBuilder queryBuilder = mStuentDao.queryBuilder();
        queryBuilder.where(StudentDao.Properties.Age.gt(age));
        List queryStudents = queryBuilder.list();
        return queryStudents;
    }

}

  • 第五步:如何调用:
package com.mrko.testone.dao;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.mrko.helper.DBStudentUtils;
import com.mrko.mydb.Student;
import com.mrko.testone.R;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class DaoTestTwoActivity extends Activity {

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_age)
    EditText etAge;
    @BindView(R.id.btn_save)
    Button btnSave;
    @BindView(R.id.btn_update)
    Button btnUpdate;
    @BindView(R.id.btn_delete)
    Button btnDelete;
    @BindView(R.id.btn_query)
    Button btnQuery;
    @BindView(R.id.listview)
    ListView listview;
    private Unbinder unbinder;
    private String mName;
    private int mAge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dao_test_two);
        unbinder = ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @OnClick({R.id.btn_save, R.id.btn_update, R.id.btn_delete, R.id.btn_query})
    public void onViewClicked(View view) {
        mName = etName.getText().toString().trim();
        String temp = etAge.getText().toString().trim();
        mAge = Integer.parseInt(temp == null || temp.equals("") ? "0" : temp);
        switch (view.getId()) {
            case R.id.btn_save:
                DBStudentUtils.getInstance().makeStudent(mName, mAge);
                break;
            case R.id.btn_update:
                DBStudentUtils.getInstance().makeStudent(mName, mAge);
                break;
            case R.id.btn_delete:
                List queryStudent = DBStudentUtils.getInstance().queryStudent(mAge);
                List deleteStudents= new ArrayList<>();
                if (queryStudent != null) {
                    for (Student student : queryStudent) {
                        KLog.e("mrko--->",student.getId() + "--" + student.getAge() + "--" + student.getName());
                        deleteStudents.add(student.getId());
                    }
                    if (deleteStudents!=null){
                        for(Long id : deleteStudents) {
                            DBStudentUtils.getInstance().deleteStudent(id);
                            KLog.e("mrko--->","delete id-->"+id);
                        }
                    }

                }
                break;
            case R.id.btn_query:
                List queryStudents = DBStudentUtils.getInstance().queryStudent(mAge);
                if (queryStudents != null) {
                    for (Student student : queryStudents) {
                        KLog.e("mrko--->" + student.getId() + "--" + student.getAge() + "--" + student.getName());
                    }
                }
                break;
        }
    }
}

  • 第六步:注意事项:

DBApplication需要在app的AndroidManifest.xml中实现android:name.. 如果重写application,继承DBAapplication、


基本接入步骤如上、当然greenDao很多探究、这里只是入门操作、、班门弄斧而已、

你可能感兴趣的:(greenDao基本使用步骤)