第一步:先导依赖

在GItHub上找到GreenDao相关的内容,然后按照步骤,依次添加到对应的build.gradle中。

// In your root build.gradle file:
buildscript {
    repositories {
        jcenter()
        mavenCentral() // add repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
    }
}

GreenDao的简单使用
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
 
dependencies {
    compile 'org.greenrobot:greendao:3.2.2' // add library
}
//在这儿可以插入

greendao {

    schemaVersion 1 //数据库版本号

    daoPackage 'com.example.greendaotest.database' //设置时生成代码的目录

    targetGenDir 'src/main/java' //设置DaoMasterDaoSessionDao目录

}

GreenDao的简单使用

//完成之后点击

GreenDao的简单使用

之后会自动生成三个文件

GreenDao的简单使用


//创建一个Application继承Application

import android.app.Application;

import com.example.day04_greendaodemo.greendao.GreenDaoUtils;

/**
 * Created by dell on 2017-12-28  14:48
 */

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        GreenDaoUtils.initGreenDao(this);
    }
}

//在清单文件中

GreenDao的简单使用


//之后就可以操作数据库了


/**
 * 
 * 创建一个GreenDaoUtils 
 */

import com.example.day04_greendaodemo.database.DaoMaster;
import com.example.day04_greendaodemo.database.DaoSession;

/**
 * Created by dell on 2017-12-28  14:45
 */

public class GreenDaoUtils {
    private static DaoSession daoSession;

    public static void initGreenDao(Context context) {
        daoSession = DaoMaster.newDevSession(context, "class.db");
    }

    public static DaoSession getDaoSession() {
        return daoSession;
    }
}

/**
 * 创建一个Student的Bean类
 */
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.DaoException;

import com.example.day04_greendaodemo.database.DaoSession;
import com.example.day04_greendaodemo.database.StudentDao;

/**
 * Created by dell on 2017-12-28  14:36
 */

@Entity(nameInDb = "MY_STUDENT", active = true)
public class Student {
    //主键必须是Long类型
    @Id(autoincrement = true)
    public Long id;
    public String name;
    public int age;
    public Long teacherID;
    /**
     * Used to resolve relations
     */
    @Generated(hash = 2040040024)
    private transient DaoSession daoSession;
    /**
     * Used for active entity operations.
     */
    @Generated(hash = 1943931642)
    private transient StudentDao myDao;

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

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

    public Long getTeacherID() {
        return this.teacherID;
    }

    public void setTeacherID(Long teacherID) {
        this.teacherID = teacherID;
    }

    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 128553479)
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }

    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 1942392019)
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }

    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 713229351)
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }

    /**
     * called by internal mechanisms, do not call yourself.
     */
    @Generated(hash = 1701634981)
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getStudentDao() : null;
    }

}
/**
 * 创建一个Teacher的Bean类
 */
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.DaoException;
import org.greenrobot.greendao.annotation.ToMany;
import org.greenrobot.greendao.annotation.Transient;

import com.example.day04_greendaodemo.database.DaoSession;
import com.example.day04_greendaodemo.database.TeacherDao;

import java.util.List;

import com.example.day04_greendaodemo.database.StudentDao;


/**
 * Created by dell on 2017-12-28  14:40
 */
@Entity(active = true)
public class Teacher {
    //主键必须是Long类型
    @Id(autoincrement = true)
    public Long id;
    public String name;
    @Property(nameInDb = "myage")
    public int age;
    @Transient
    public boolean gender;
    @ToMany(referencedJoinProperty = "teacherID")
    List<Student> studentList;
    /**
     * Used to resolve relations
     */
    @Generated(hash = 2040040024)
    private transient DaoSession daoSession;
    /**
     * Used for active entity operations.
     */
    @Generated(hash = 648119699)
    private transient TeacherDao myDao;

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

    @Generated(hash = 1630413260)
    public Teacher() {
    }

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

    /**
     * To-many relationship, resolved on first access (and after reset).
     * Changes to to-many relations are not persisted, make changes to the target entity.
     */
    @Generated(hash = 927304389)
    public List<Student> getStudentList() {
        if (studentList == null) {
            final DaoSession daoSession = this.daoSession;
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            StudentDao targetDao = daoSession.getStudentDao();
            List<Student> studentListNew = targetDao._queryTeacher_StudentList(id);
            synchronized (this) {
                if (studentList == null) {
                    studentList = studentListNew;
                }
            }
        }
        return studentList;
    }

    /**
     * Resets a to-many relationship, making the next get call to query for a fresh result.
     */
    @Generated(hash = 1628625923)
    public synchronized void resetStudentList() {
        studentList = null;
    }

    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 128553479)
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }

    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 1942392019)
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }

    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 713229351)
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }

    /**
     * called by internal mechanisms, do not call yourself.
     */
    @Generated(hash = 1349174479)
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getTeacherDao() : null;
    }
}

/*
 *在MainActivity中操作数据库
 * 
 */
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.example.day04_greendaodemo.database.DaoSession;
import com.example.day04_greendaodemo.database.StudentDao;
import com.example.day04_greendaodemo.database.TeacherDao;
import com.example.day04_greendaodemo.greendao.GreenDaoUtils;
import com.example.day04_greendaodemo.greendao.Student;
import com.example.day04_greendaodemo.greendao.Teacher;

import org.greenrobot.greendao.query.Query;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private DaoSession daoSession;
    private StudentDao studentDao;
    private TeacherDao teacherDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化数据库
        daoSession = GreenDaoUtils.getDaoSession();
        studentDao = daoSession.getStudentDao();
        teacherDao = daoSession.getTeacherDao();

    }

    /**
     * 添加数据库
     *
     * @param view
     */
    public void add(View view) {
        Teacher teacherWang = new Teacher(null, "小王", 18);
        Teacher teacherFan = new Teacher(null, "小龙", 28);
        Teacher teacherZhao = new Teacher(null, "小振", 38);
        teacherDao.insertInTx(teacherFan, teacherWang, teacherZhao);

        Student xiaoHua = new Student(null, "小花", 18, teacherFan.getId());
        Student xiaoMing = new Student(null, "小明", 20, teacherWang.getId());
        Student xiaoTian = new Student(null, "小天", 22, teacherZhao.getId());
        studentDao.insertInTx(xiaoHua, xiaoMing, xiaoTian);
    }

    /**
     * 删除数据库
     *
     * @param view
     */
    public void delete(View view) {
        /*Teacher teacher = teacherDao.queryBuilder()
                .where(TeacherDao.Properties.Name.eq("小王"))
                //只会查询出一个,如果数据库有多个的话,会抛异常
                .unique();
        teacherDao.deleteByKey(teacher.getId());*/
        //teacherDao.delete(teacher);
        teacherDao.deleteAll();

    }

    /**
     * 修改数据库
     *
     * @param view
     */
    public void update(View view) {
        Teacher teacher = teacherDao.queryBuilder()
                .where(TeacherDao.Properties.Name.eq("小王"))
                //只会查询出一个,如果数据库有多个的话,会抛异常
                .unique();
        teacher.setAge(20);
        teacherDao.update(teacher);
    }

    /**
     * 查询数据库
     *
     * @param view
     */

    //在子线程查询
    public void query(View view) {
        new Thread() {
            @Override
            public void run() {
                Query<Teacher> query = teacherDao.queryBuilder()
                        .where(TeacherDao.Properties.Name.eq("小王"))
                        //只会查询出一个,如果数据库有多个的话,会抛异常
                        .build();
                List<Teacher> list = query.forCurrentThread().list();
            }
        }.start();
    }
}

//布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.day04_greendaodemo.MainActivity">

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:onClick="add"
        android:text="add" />

    <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/add"
        android:layout_marginTop="20dp"
        android:onClick="delete"
        android:text="delete" />

    <Button
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/delete"
        android:layout_marginTop="20dp"
        android:onClick="update"
        android:text="update" />

    <Button
        android:id="@+id/query"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/update"
        android:layout_marginTop="20dp"
        android:onClick="query"
        android:text="query" />
    
</RelativeLayout>




相关文章: