GreenDao使用方式

本文介绍了如何在项目中使用GreenDao,从配置gradle,到MyApplication的初始化,再到Bean类的设计,如@Entity注解的使用,以及@Id的设置。文章还提到了@Convert在处理复杂数据类型如子类或list时的作用,并指出通过构建项目,GreenDao会自动生成相关代码和Dao文件,简化开发流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用过litepal,抛弃litepal是因为多层级时数据插入查询太慢了,greendao也没有进项大量数据测试,也是尝试阶段。
1.项目gradle

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

app.gradle

apply plugin: 'org.greenrobot.greendao'
android{
    greendao {
        //数据库版本号,升级时修改
        schemaVersion 1
        //生成的DAO,DaoMaster和DaoSession的包路径。默认与表实体所在的包路径相同
        daoPackage '你的包名'
        //生成源文件的路径。默认源文件目录是在build目录中的(build/generated/source/greendao)
        targetGenDir 'src/main/java'
    }
    }
dependencies {
    implementation 'org.greenrobot:greendao:3.2.0'
    implementation 'io.github.yuweiguocn:GreenDaoUpgradeHelper:v2.2.1'
    implementation 'com.google.code.gson:gson:2.6.2'
}

2.MyApplication要进行初始化

    public static MyApplication getApplication() {
        return application;
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "greenDbbao.db");
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

3.Bean类
Person.class
@Entity是将类进行greendao自动生成标识
@Id 是表key ,long型,我习惯单独定义方便控制
@Convert是将子类或者list转换为String
Student_Convert 和StudentList_Convert要提前写好

package com.tayh.buttontest.greendao;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.greendao.annotation.Convert;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.converter.PropertyConverter;

import java.util.List;

/**
 * @author 
 * @time 2020-03-14.
 */
@Entity
public class Person {
    @Id
    private Long idss;
    private int age;
    private String name;
    private int sex;
    @Convert(columnType = String.class, converter = Student_Convert.class)
    private Student stud;
    @Convert(columnType = String.class, converter = StudentList_Convert.class)
    private List<Student> students;
       
    public static class Student_Convert implements PropertyConverter<Student,String>{

        @Override
        public Student convertToEntityProperty(String databaseValue) {
            if (databaseValue == null) {
                return null;
            }
            return new Gson().fromJson(databaseValue, Student.class);
        }

        @Override
        public String convertToDatabaseValue(Student entityProperty) {
            if (entityProperty == null) {
                return null;
            }
            return new Gson().toJson(entityProperty);
        }
    }
    
    public static class StudentList_Convert implements PropertyConverter<List<Student>,String>{

        @Override
        public List<Student> convertToEntityProperty(String databaseValue) {
            if (databaseValue == null) {
                return null;
            }
            // 先得获得这个,然后再typeToken.getType(),否则会异常
            TypeToken<List<Student>> typeToken = new TypeToken<List<Student>>(){};
            return new Gson().fromJson(databaseValue, typeToken.getType());
        }

        @Override
        public String convertToDatabaseValue(List<Student> entityProperty) {
            if (entityProperty == null||entityProperty.size()==0) {
                return null;
            } else {
                String sb = new Gson().toJson(entityProperty);
                return sb;

            }
        }
    }

    public static class Student{
        private Long ide;
        private int index;

        public Student(int index, String name) {
            this.index = index;
            this.name = name;
        }

        private String name;
    }
}

点击build->make Project会自动生成代码,并生成PersonDao文件,不需要修改

package com.tayh.buttontest.greendao;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.greendao.annotation.Convert;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.converter.PropertyConverter;

import java.util.List;

/**
 * @author LZY
 * @time 2020-03-14.
 */
@Entity
public class Person {
    @Id
    private Long idss;
    private int age;
    private String name;
    private int sex;
    @Convert(columnType = String.class, converter = Student_Convert.class)
    private Student stud;
    @Convert(columnType = String.class, converter = StudentList_Convert.class)
    private List<Student> students;
    @Generated(hash = 1997124674)
    public Person(Long idss, int age, String name, int sex, Student stud, List<Student> students) {
        this.idss = idss;
        this.age = age;
        this.name = name;
        this.sex = sex;
        this.stud = stud;
        this.students = students;
    }
    @Generated(hash = 1024547259)
    public Person() {
    }
    public Long getIdss() {
        return this.idss;
    }
    public void setIdss(Long idss) {
        this.idss = idss;
    }
    public int getAge() {
        return this.age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSex() {
        return this.sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public Student getStud() {
        return this.stud;
    }
    public void setStud(Student stud) {
        this.stud = stud;
    }
    public List<Student> getStudents() {
        return this.students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }

    public static class Student_Convert implements PropertyConverter<Student,String>{

        @Override
        public Student convertToEntityProperty(String databaseValue) {
            if (databaseValue == null) {
                return null;
            }
            return new Gson().fromJson(databaseValue, Student.class);
        }

        @Override
        public String convertToDatabaseValue(Student entityProperty) {
            if (entityProperty == null) {
                return null;
            }
            return new Gson().toJson(entityProperty);
        }
    }

    public static class StudentList_Convert implements PropertyConverter<List<Student>,String>{


        @Override
        public List<Student> convertToEntityProperty(String databaseValue) {
            if (databaseValue == null) {
                return null;
            }
            // 先得获得这个,然后再typeToken.getType(),否则会异常
            TypeToken<List<Student>> typeToken = new TypeToken<List<Student>>(){};
            return new Gson().fromJson(databaseValue, typeToken.getType());
        }

        @Override
        public String convertToDatabaseValue(List<Student> entityProperty) {
            if (entityProperty == null||entityProperty.size()==0) {
                return null;
            } else {
                String sb = new Gson().toJson(entityProperty);
                return sb;

            }
        }
    }

    public static class Student{
        private Long ide;
        private int index;

        public Student(int index, String name) {
            this.index = index;
            this.name = name;
        }

        private String name;
    }
}

4.GreenDaoManager对数据进行处理帮助类

package com.tayh.buttontest.greendao;

import com.tayh.buttontest.MyApplication;
import com.tayh.buttontest.greendao.auto.PersonDao;

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

/**
 * @author LZY
 * @time 2020-03-15.
 */
public class GreenDaoManager {

    private static final String TAG = "GreenDaoManager";

    private static GreenDaoManager instance;

    private PersonDao personDao;

    public static GreenDaoManager getInstance() {
        if (instance == null) {
            synchronized (GreenDaoManager.class) {
                if (instance == null) {
                    instance = new GreenDaoManager();
                }
            }
        }
        return instance;
    }

    private GreenDaoManager() {
        personDao = MyApplication.getApplication().getDaoSession().getPersonDao();
    }

    public List<Person> getPersonList(){
        List<Person> personList = new ArrayList<>();
        personList = personDao.loadAll();
        return personList;
    }

    public void savePerson(Person person) {
        person.setIdss(null);//保证都是新增
        personDao.save(person);
    }

    public void delPerson(Person person) {//通过查询删除搜索词相同的
        personDao.queryBuilder()
                .where(PersonDao.Properties.Name.eq(person.getName()))
                .where(PersonDao.Properties.Age.eq(person.getAge()))
                .buildDelete().executeDeleteWithoutDetachingEntities();
    }

    public void delPersonList(Person person) {
        List<Person> delList = new ArrayList<>();//删除搜索key相同的
        for (Person bean : getPersonList()) {
            if (bean.getAge() == person.getAge()) {
                delList.add(bean);
            }
        }
        personDao.deleteInTx(delList);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值