Android中GreenDao對數據庫進行升級操做筆記

1、修改app中build.gradle的greendao的配置的schemaVersionjava

greendao {
    //指定數據庫schema版本號,遷移等操做會用到
    schemaVersion 1 
     //經過gradle插件生成的數據庫相關文件的包名,默認爲你的entity所在的包名
    daoPackage 'com.companyName.projectName.dao'
     /*這就是咱們上面說到的自定義生成數據庫文件的目錄了,
    能夠將生成的文件放到咱們的java目錄中,
    而不是build中,這樣就不用額外的設置資源目錄了*/
    targetGenDir 'src/main/java'
}

2、修改實體類數據庫

添加或刪除實體類的屬性app

@Entity
public class User {
    @Id
    private Long id;
    @Property
    private String userName;
    @Property
    private String password;
    @Property
    private String email;//新增屬性
}

通常的數據庫升級這樣就能夠了,特殊狀況可能須要本身編寫數據庫遷移腳本,這種時候能夠自定義DBHelper,定義方式以下,注意繼承類:ide

public class DBHelper extends DaoMaster.OpenHelper{


    public DBHelper(Context context, String name) {
        super(context, name);
    }

    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);
    }

    @Override
    public void onCreate(Database db) {
        super.onCreate(db);
    }

    //在onUpgrade的方法裏重寫本身的代碼
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        super.onUpgrade(db, oldVersion, newVersion);
    }
}

能夠在onUpgrade方法中進行數據庫的遷移,若是自定義了DBHelper,則數據庫的初始化變爲以下方式:gradle

public class DBManager {

    private DaoMaster daoMaster;
    //此處換成DBHelper
    private DBHelper helper;
    //private DaoMaster.DevOpenHelper helper;
    private DaoSession daoSession;
    private SQLiteDatabase db;

    private static DBManager instance;

    public static DBManager getInstance() {
        if (instance == null) {
            instance = new DBManager();
        }
        return instance;
    }

    private void initDB(Context context) {
        helper = new DBHelper(context, "yourDatabaseName", null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    public DaoSession getDaoSession(Context context) {
        if (daoSession == null) {
            initDB(context);
        }
        return daoSession;
    }
}
相關文章
相關標籤/搜索