How to transfer from a table without a primary key using a room?

I am trying to go into the room, but the layout of my table was like this:

CREATE TABLE cache(key text, content text, time integer);

Entity:

@Entity(tableName = "cache")
public class Cache{
    public Integer id;
    public String key;
    public String content;
    public Integer time;
}

No primary key was declared explicit, an error occurred during assembly:

An entity must have at least 1 field annotated with @PrimaryKey

I tried adding a primary key to the table, but sqlite doesn't seem to support this, can anyone help me?

+4
source share
2 answers

Excerpt from here: http://www.sqlitetutorial.net/sqlite-primary-key/

Unlike other database systems, such as MySQL, PostgreSQL, etc., you cannot use the ALTER TABLE statement to add a primary key to an existing table.

To get around this, you need to:

  • Set foreign key
  • Rename the table to another table name (old_table)
  • () ,
  • old_table
0

, ,

 static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(android.arch.persistence.db.SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE cache ADD COLUMN id INTEGER primary KEY AUTOINCREMENT");
        }
    };

MigrationRule

Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DATABASE_NAME)
        .addMigrations(MIGRATION_1_2)
        .allowMainThreadQueries()
        .build();

@Entity(tableName = "cache")
public class Cache{
    @PrimaryKey(autoGenerate = true)
    public Integer id;
    public String key;
    public String content;
    public Integer time;
}

, SQLite db + 1

0

Source: https://habr.com/ru/post/1696106/


All Articles