Little tricks you should know about Greendao.

Source: Internet
Author: User
Tags static class
"Preface"

I believe you have used Greendao in development. Not yet, build it up, now!),
Is deeply attracted by its lightness, convenience, rapidity and efficiency. Haha, this blog,
It's not about how it's used or how it's implemented. Yes, that's what you'll encounter in development,
After the database upgrade, how to ensure that the original data is not lost. "Background description"

Assuming that the first version of the app requires only a single table student, this table has only two attributes (except the ID), name and
Age Due to project requirements, to add attribute profession to the student table, this is required in the second app
Version to upgrade the database version number. Then there is a new demand for the project, and a table teacher is added, and the properties of this table
With name and age (in addition to the ID), you need to upgrade the database version in the third version of the app.
In a two-time database version upgrade, if you simply drop the history table and recreate the tables, you can
Synchronize updates to the table. However, the data in the historical version will be lost and will result in a very poor user experience. "About Daomaster.devopenhelper"

Greendao The default generated Daomaster, which has a static inner class devopenhelper. Its role is to
Manage the creation and upgrade of databases. Where the upgraded function Onupgrade is implemented as follows:

@Override public
   void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
       log.i ("Greendao", " Upgrading schema from version ' + oldversion + ' to ' + NewVersion + ' by dropping all Tables ');
       Dropalltables (db, true);
       OnCreate (db);
   }

As you can see, when you upgrade a database, Greendao calls the upgrade database, dropping all historical tables,
Then recreate all the tables, which leads to the loss of historical data. "Solution Ideas"

A database Upgrade management class is required, such as Upgrademanager, and the code is implemented as follows:

public class Upgrademanager {public

    static void Onupgrade (Sqlitedatabase db, int oldversion) {
        switch (oldversio N) {
            Case 1:
                /**
                 * Student table Add field profession
                 *
                /Db.execsql ("ALTER TABLE Student add column Profession Text ");


                /**
                 * Database Add Table Teacher
                 *
            /Case 2:
                teacherdao.createtable (db, false);


            Default: Break;}}}

 

Note: The upgrade requirement for the first database version is to add field profession to the student table, so
Use the alter of the SQL statement to add fields to the table student. Data requirements for the second database version are,
Add Table teacher, you can use the Greendao encapsulated code to create the table (of course, you can also write the original
Generation of SQL statements). If the user uses version 2
Apps that are installed in version 1 will be executed from Case 1. If the user is using version 3 of the app
Overwrite the app with version 2 installed, which starts with Case 2. This is achieved by preserving the history
Data, but also hit the purpose of database upgrade.

Note: There is no break in the case here. Because, if a break is added, suppose the user downloads version 3APP
Overwrite installs version 1APP, this time executes case 1, but does not execute cases 2, causes the teacher table
was not created. Another key point is that the order of the case must follow the order of requirements for each upgrade of the database
Add to. For example, the first requirement is to increase the student table field profession, and the second demand is the new
Table Teacher. "Code Call"

The Onupgrade method of Upgrademanager is called in the Onupgrade of Devopenhelper, as follows:

 
@Override public
   void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
       log.i ("Greendao", " Upgrading schema from version ' + oldversion + ' to ' + NewVersion + ' by dropping all Tables ');
       Dropalltables (db, true);
       OnCreate (db);
       Upgrademanager.onupgrade (DB, oldversion);
   }
 

Note: Comment out the automatically generated dropalltables and OnCreate, and replace the actual call Upgrademanager.onupgrade.
The Onupgrade is regenerated every time Greendao compilation is automatically generated Daomaster, so
After each database version upgrade, remember to perform the above changes (if you want to do this, you can download
Greendao source code, modify the Dao-master.flt generation rules can be) "Demo" 1, before the change of requirements

 
public class Generatorclass {public

    static void Main (string[] args) {
        try {

            /**
             * Parameter: Version number: Package name
            */ Schema schema = new schema (1, "Com.jay.greendao");

            Corresponding student table
            Entity student = schema.addentity ("student");
            Student.addidproperty ();
            Student.addstringproperty ("name"). Notnull ();
            Student.addintproperty ("Age");

            /**
             * Code generation path, self-setting */
            new Daogenerator (). Generateall (Schema, "d:\\sources\\greendaodemo\\app\\src\ \main\\java-gen ");
        } catch (Exception e) {
            e.printstacktrace ();}}
}
 

Note: At this point the database version number is 1.

Then, add a student data to the table:

 
private void Insertstudent () {
       Studentdao Studentdao = Daosession.getstudentdao ();
       Student Student = new Student ();
       Student.setname ("Jay");
       Student.setage ();
       Studentdao.insert (student);
   }
 

View Table Studen:

2, Requirements 1--student table added field profession

 
public class Generatorclass {public

    static void Main (string[] args) {
        try {

            /**
             * Parameter: Version number: Package name
            */ Schema schema = new schema (2, "Com.jay.greendao");
            Corresponding student table
            Entity student = schema.addentity ("student");
            Student.addidproperty ();
            Student.addstringproperty ("name"). Notnull ();
            Student.addintproperty ("Age");
            Demand one
            student.addstringproperty ("profession");
            /**
             * Code generation path, self-setting */
            new Daogenerator (). Generateall (Schema, "d:\\sources\\greendaodemo\\app\\src\ \main\\java-gen ");
        } catch (Exception e) {
            e.printstacktrace ();}}
}
 

Description: The database version number was changed to 2 and a new Student.addstringproperty ("profession") was added.

The key point is to modify the automatically generated Daomaster.devopenhelper Onupgrade, as follows:

 
public static class Devopenhelper extends Openhelper {public
    Devopenhelper (context context, String name, Cursorfacto Ry Factory) {
        Super (context, name, Factory);
    }

    @Override public
    void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
        log.i ("Greendao", " Upgrading schema from version ' + oldversion + ' to ' + NewVersion + ' by dropping all Tables ');            dropalltables (db, true);            onCreate (db);
        Upgrademanager.onupgrade (DB, oldversion);
    }
}

The code for Upgrademanager is as follows:

 
public class Upgrademanager {public

    static void Onupgrade (Sqlitedatabase db, int oldversion) {
        switch (oldvers ION) {
            Case 1:
                /**
                 * Student table Add field profession
                 *
                /Db.execsql ("ALTER TABLE Student add column Profession text ");
            Default: Break;}}}

 

Description: Compile the build version 2 app at this point, and the correct case is to keep the historical data and add the profession field:

3, demand 2--new table teacher

 public class Generatorclass {public static void main (string[] args) {try {/**
            * Parameters: Version number: Package name */Schema schema = new schema (3, "Com.jay.greendao");
            Corresponding student table Entity student = schema.addentity ("student");
            Student.addidproperty ();
            Student.addstringproperty ("name"). Notnull ();
            Student.addintproperty ("Age");

            Demand one student.addstringproperty ("profession");
            Requirement two, added table teacher Entity teacher = schema.addentity ("Teacher");
            Teacher.addidproperty ();
            Teacher.addstringproperty ("name"). Notnull ();
            Teacher.addintproperty ("Age"); /** * Code generation path, self-setting */New Daogenerator (). Generateall (Schema, "d:\\sources\\greendaod
        Emo\\app\\src\\main\\java-gen ");
        } catch (Exception e) {e.printstacktrace (); }
    }
}
 

Note: At this point the database version number is 3 and a new table teacher is added.

* Do not forget to modify the auto-generated daomaster, the same as above. *
Then insert a piece of data into the teacher table, as follows:

private void Insertteacher () {
      Teacherdao Teacherdao = Daosession.getteacherdao ();
      Teacher Teacher = new Teacher ();
      Teacher.setname ("Jom");
      Teacher.setage (a);
      Teacherdao.insert (teacher);
  }
 

The Upgrademanager changes are as follows:

public class Upgrademanager {public

    static void Onupgrade (Sqlitedatabase db, int oldversion) {
        switch (oldversi On) {
            Case 1:
                /**
                 * Student table Add field profession
                 *
                /Db.execsql ("ALTER TABLE Student add column Profession text ");

                /**
                 * Database Add Table Teacher
                 *
            /Case 2:
                teacherdao.createtable (db, false);

            Default: Break;}}}

At this time, the historical data should be preserved while the new table teacher,

"Summary"

The above implementation, can be a good solution to the problem of data loss. Welcome to the message, mutual exchange of learning. More about Greendao
For advanced usage, we recommend visiting Greendao official website.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.