简体   繁体   中英

How to creatle table using migration in Room database?

 Expected:
    TableInfo{name='role', columns={title=Column{name='title', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}}, foreignKeys=[], indices=[]}
     Found:
    TableInfo{name='role', columns={id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, title=Column{name='title', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}

I'm trying to make migration and I don't understand where is the problem. I see title is the first row, but I do not understand why. In RoleRoom we can see directly it is on the second place... How to fix it? :)

@TypeConverters(RoomConverters::class)
@Entity(tableName = "role")
class RoleRoom(
    @PrimaryKey val id: Int = 0,
    val title: String
)

in Migration class

        database.execSQL("CREATE TABLE IF NOT EXISTS `role` (`id` INTEGER, `title` TEXT, PRIMARY KEY(`id`))")

The issues are that Room expects non nullables to be NOT NULL. That is Int and String are not nullable. So Room expects

CREATE TABLE IF NOT EXISTS `role` (`id` INTEGER NOT NULL, `title` TEXT NOT NULL, PRIMARY KEY(`id`))")

Hence the expected has .... notNull=true.... notNull=true whilst the found has .... notNull=false.... notNull=false

However, rather than trying to interpret the @Entity annotated class, it is simpler to let Room do the work. That is if you

  1. Create the @Entity annotated class(es) as required
  2. Add the @Entity annotated class(es) to the entities parameter of the @Database annotated abstract class.
  3. Compile the project (CTRL + F9).
  4. From the Android View look for the java(generated) folder/directory, expand the directories and locate the class that is the same name as the @Database annotated class, but suffixed with _Impl .
  5. Within the class, locate the createAllTables method, and you will find code that exceutes the SQL for creating the tables with EXACTLY the SQL that Room expects.
    1. Note that the code for room_master_table should be ignored as Room will create the table and populate it itself.
  6. Copy the respective SQL and use that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM