Search code examples
androidormlite

ORMLite query string for serializable object


I added a new column in an entity like:

@DatabaseField(persisterClass = SerializableType.class)
Account account;

The table is already created in the previous app version. So in OrmLiteSqliteOpenHelper, I have to execute one query string inside function:

@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
    try {
        if (oldVersion < 2) {
            String userTable = DatabaseTableConfig.extractTableName(User.class);
            getDao(User.class).executeRaw("ALTER TABLE `" + userTable + "` ADD COLUMN account SERIALIZABLE;");
        }
    } catch (SQLException e) {

    }
}

What should be the query string? Is the query string alter table xyz add column abc serializable correct? Or is there any other possible ways to add serializable object in existing table?


Solution

  • OrmLite persists serializable object as SQL type VARBINARY. This is a special type that serializes an object as a sequence of bytes and then de-serializes it on the way back. The field must be an object that implements the java.io.Serializable interface. Depending on the database type, there will be limits to the size of the object that can be stored

    NOTE: To use this type, you must specify DataType.SERIALIZABLE using the dataType field. It will not be auto-detected. See DatabaseField dataType.

    // account is an object that implements Serializable
    @DatabaseField(dataType = DataType.SERIALIZABLE)
    Account account;
    

    You can also define and register your own persister like in this thread.