mercredi 2 septembre 2015

Android/Java SQL database independence from entity

I have a low experience in DB design and development with SQL.

I have Entity User :

public class User {
    String name;
    String secondName;
}

and DAO for this :

public interface UserDAO {
    // save
    void persistUser(User user);
    // obtain from DB
    User retrieveUser();
}

Implementation :

public class LibraryUserDAO implements UserDAO{

    /** SQL database actually*/    
    private SQLiteOpenHelper database;

    void persistUser(User user){
        // saving to DB
    }

    User retrieveUser(){
        // obtain from DB
    }
}

And i have a question.

Is it possible to make saving to DB process independent for User class changes?

For example : now, as you can see i have 2 fields - name and secondName

Saving now :

    SQLiteDatabase writableDatabase = database.getWritableDatabase();
    writableDatabase.beginTransaction();

    ContentValues cv = new ContentValues();
    cv.put("name", user.name);
    cv.put("secondName", user.secondName);

    writableDatabase.insert("users", null, cv);
    writableDatabase.close();

I want that when you add a new field (for ex. year) to the class User, in the database, this field is automatically added as a new column in the database (if not). So always leave class SQLiteOpenHelper unchanged.(If it possible of course).

Aucun commentaire:

Enregistrer un commentaire