Simple use of GreenDao 2

Posted by becoolufull on Sat, 08 Jun 2019 20:37:53 +0200

Advancement of Green Dao

In the introduction to the use of greendao in the last article, we learned that using XXXDao can accomplish some basic operations of the database, such as adding, deleting, modifying and checking.

Recall again the three core classes that are automatically generated: DaoMaster, DaoSession, XXXDao

  • DaoMaster is called the session layer. DaoMaster contains a DevOpenHelper (inherited from OpenHelper). DevOpenHelper contains basic operations for databases, such as creating tables, deleting tables, updating tables. It is worth mentioning that the way to upgrade databases in the DevOpenHelper class is to delete all tables first, and then recreate tables, and all data will disappear. Please refer to the steps above greendao 3.0 (2): How to upgrade the database in the end http://blog.csdn.net/huangxiaoguo1/article/details/54574713
  • DaoSession manages the XXXDao.class class class and also provides a way to add, delete and modify checks (in fact, AbstractDao abstract class is used)
  • The Dao class corresponding to each table entity (Entity) of XXXDao provides a series of operations such as data addition, deletion, modification, and so on, which is more specific than the method provided by the DaoSession class.

Steps for using GreenDao to manipulate data in a project:

1. (Recommendation) Maintain a DaoManager class to retrieve DaoMaster and DaoSession instances, for example:

public class DaoManager {
    //Database name
    private static final String DB_NAME = "student.db";

    private Context mContext;
    //Singleton pattern
    private volatile static DaoManager mDaoManager;

    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private DaoMaster.DevOpenHelper mOpenHelper;

    private DaoManager(Context context) {
        this.mContext = context;
    }

    public static DaoManager getInstance(Context context) {
        if (mDaoManager == null) {
            synchronized (DaoManager.class) {
                mDaoManager = new DaoManager(context);
            }
        }

        return mDaoManager;
    }

    /**
     * Determine whether a database exists or not, and if not, create a database
     *
     * @return
     */
    public DaoMaster getDaoMaster() {
        if (mDaoMaster == null) {
            mOpenHelper = new DaoMaster.DevOpenHelper(mContext, DB_NAME);

            //Complete the creation of database
            mDaoMaster = new DaoMaster(mOpenHelper.getWritableDatabase());
        }
        return mDaoMaster;
    }


    public DaoSession getDaoSession() {
        if (mDaoSession == null) {
            if (mDaoMaster == null) {
                mDaoMaster = getDaoMaster();
            }
            mDaoSession = mDaoMaster.newSession();
        }

        return mDaoSession;
    }


    /**
     * The operation of opening the output log is turned off by default
     */
    public void setDebug() {
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
    }

    /**
     * Close
     */
    public void closeDaoSession() {
        if (mDaoSession != null) {
            mDaoSession.clear();
            mDaoSession = null;
        }
    }

    public void closeHelper() {
        if (mOpenHelper != null) {
            mOpenHelper.close();
            mOpenHelper = null;
        }
    }

    /**
     * Close database connection
     */
    public void closeDBConncetion() {
        closeDaoSession();
        closeHelper();
    }

}

2. Create the dao corresponding to each table table table, as follows

public class StudentDaoManager {
    private DaoManager mDaoManager;

    private StudentDaoManager(Context context) {
        mDaoManager = DaoManager.getInstance(context);
    }

    //Singleton pattern
    private static volatile StudentDaoManager mStudentDaoManager;

    public static StudentDaoManager getInstance(Context context) {
        if (mStudentDaoManager == null) {
            synchronized (StudentDaoManager.class) {
                if (mStudentDaoManager == null) {
                    mStudentDaoManager = new StudentDaoManager(context);
                }
            }
        }

        return mStudentDaoManager;
    }

    /**
     * Insert single data
     *
     * @param student Data to be inserted
     * @return Successful insertion
     */
    public boolean insertStu(Student student) {
        boolean flag = false;
        flag = mDaoManager.getDaoSession().getStudentDao().insert(student) != -1 ? true : false;
        return flag;
    }

    /**
     * Insert or update a single piece of data. If the data already exists, update that piece of data.
     *
     * @param student
     * @return Successful insertion
     */
    public boolean insertOrReplace(Student student) {
        boolean flag = false;
        flag = mDaoManager.getDaoSession().getStudentDao().insertOrReplace(student) != -1 ? true : false;
        return flag;
    }


    /**
     * Insert multiple data
     *
     * @param isUseTra Whether to use things or not
     * @param list     List of data to be inserted in batches
     * @return Successful insertion
     */
    public boolean insertMutiStus(boolean isUseTra, List<Student> list) {
        boolean flag = false;
        try {

            if (isUseTra) {
                //Using batch insertion of things
               mDaoManager.getDaoSession().getStudentDao().insertOrReplaceInTx(list);

            } else {
                for (Student student : list) {
                    //Using the usual method, insert a single bar
                    mDaoManager.getDaoSession().getStudentDao().insertOrReplace(student);
                }
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * Delete single data
     *
     * @param student
     * @return Successful insertion
     */
    public boolean delete(Student student) {
        boolean flag = false;
        try {
            mDaoManager.getDaoSession().getStudentDao().delete(student);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * Update data
     *
     * @param student Data to be updated
     * @return Successful insertion
     */
    public boolean update(Student student) {
        boolean flag = false;
        try {
            mDaoManager.getDaoSession().getStudentDao().update(student);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * Return all data
     *
     * @return list
     */
    public List<Student> queryAll() {
        List<Student> students = mDaoManager.getDaoSession().getStudentDao().loadAll();
        return students;
    }

    /**
     * Returns a single record
     *
     * @param studentId Student Object ID, primary key
     * @return single record
     */
    public Student queryOne(long studentId) {
        return mDaoManager.getDaoSession().getStudentDao().load(studentId);
    }

    /**
     * Paging query
     *
     * @param limit  Number of query records
     * @param offset Initial location of query
     * @return
     */
    public List<Student> queryOffset(int limit, int offset) {
        QueryBuilder<Student> builder = mDaoManager.getDaoSession().getStudentDao().queryBuilder();
        builder.offset(offset).limit(limit);
        List<Student> list = builder.list();
        return list;
    }

    /**
     * Query Builder is used for queries.
     *
     * @return
     */
    public List<Student> queryWithBuilder() {
        QueryBuilder<Student> builder = mDaoManager.getDaoSession().getStudentDao().queryBuilder();
        //1. The use of where (all where are logical and related, equivalent to and) corresponds to: select * from student where name like "% music" and sex = male;
        builder.where(StudentDao.Properties.Name.like("%Happy")).where(StudentDao.Properties.Sex.eq("male"));
        //2. The above equivalent:
//        builder.where(StudentDao.Properties.Name.like("% music"), StudentDao.Properties.Sex.eq("male");

        //3. Logic or, equivalent to or, concatenates many query conditions
        builder.whereOr(StudentDao.Properties.Name.like("%Happy%"), StudentDao.Properties.Sex.eq("male"));

        //4. The query results in 1 are the same.
        List<Student> students = mDaoManager.getDaoSession().getStudentDao().queryRaw("where name like ? and sex = ?", new String[]{"%Happy%", "male"});
        List<Student> studentList = builder.list();
        return students;
    }
}

The above code is a bit long. It should be noted that:

1. When using transaction to insert data into database, open transaction should be adopted for large amount of data.

//Using batch insertion of things
mDaoManager.getDaoSession().getStudentDao().insertOrReplaceInTx(list);

You can see that you can just pass in a List object directly. What's more, if there is a data insertion error in the process of batch insertion, the transaction will roll back to the state before insertion. The opening and closing of the transaction has been encapsulated for us in greendao, so we don't need to worry about it.

Query Builder is a good thing for programmers who are not familiar with SQL. Let's see how to use it first.

QueryBuilder<Student> builder = mDaoManager.getDaoSession().getStudentDao().queryBuilder();
        //1. The use of where (all where are logical and related, equivalent to and) corresponds to: select * from student where name like "% music" and sex = male;
        builder.where(StudentDao.Properties.Name.like("%Happy")).where(StudentDao.Properties.Sex.eq("male"));
        //2. The above equivalent:
//        builder.where(StudentDao.Properties.Name.like("% music"), StudentDao.Properties.Sex.eq("male");

        //3. Logic or, equivalent to or, concatenates many query conditions
        builder.whereOr(StudentDao.Properties.Name.like("%Happy%"), StudentDao.Properties.Sex.eq("male"));

        //4. The query results in 1 are the same.
        List<Student> students = mDaoManager.getDaoSession().getStudentDao().queryRaw("where name like ? and sex = ?", new String[]{"%Happy%", "male"});

3. We know that XXXDao is inherited from AbstractDao. XXXDao encapsulates the basic method of adding and deleting modification checking. DaoSession also contains the basic method of adding and deleting modification checking. When maintaining XXXDao, just like in the example code above, I define a Student Dao Manager, which contains many methods of adding and deleting modification checking. This Student Dao Manager only aims at one table. It's Student, and there must be many tables in the database in the daily development. Doesn't it increase the repeatability of development if we write a DaoManager for one table? So I suggest that we ignore the automatic generation of XXXDao directly and use the method of adding, deleting and modifying in DaoSession to operate the database data directly. The examples are as follows:

//Insert data, T is generic
public void insert(T t) {
    mDaoManager.getDaoSession().insert(t);
}

In this way, all tables in the database can use this method instead of maintaining a Dao without an Entity.

** 4.**Properties is an internal class of Student Dao, which maintains the column names of each table entity.
For more meanings of greendao keywords like where, where Or, like, and so on, please refer to the official greendao API.( http://greenrobot.org/files/greendao/javadoc/current/)

Topics: Database Session SQL