akash
akash

Reputation: 167

how to write migration for newly added table in room database android

Can someone help me here, As i wanted to alter existing room table(User) by adding new column which is object(address). `

 data class UserDetailsEntity (
  @PrimaryKey
  var id: Int = 0,

  @ColumnInfo(name ="name")
    val name:String? = null,

  @ColumnInfo(name = "lastName")
  val lastName: String ?= null,  
 
  @Embedded
  val address:Address ?= null, 

)
 
data class Address (

@ColumnInfo(name ="lat")
 val lat : String? = null,

@ColumnInfo(name = "long")
 val long: String ?= null,  

)

` How to write migration for above scenario? Thanks in advance.

Upvotes: 1

Views: 1975

Answers (1)

MikeT
MikeT

Reputation: 56938

Do I need to write migration for this? (from comment)

Yes as the table is being altered.

By Embedding the Address then room will consider that a UserDetailsEntity object will have an Address object within it. Room will therefore build the code to set the objects values.

Additionally room will expect the table UserDetailsEntity (or whatever value is associated with the table) to have two extra columns lat and long. Therefore the migration needs to add the 2 columns. You would use 2 ALTER TABLE <tablename> ADD COLUMN <column_definition>; in the migration.

  • Note if you compile (Ctrl + F9) with the changes made then look in the Java(generated) subfolders, whilst in Android view of the Project window, and then look at the class, followed by _impl where you have the @Database in the createAllTables method. The SQL for the creation of the table will exist. You can then copy and paste the column definitions.
  • Example screen shot where the class Database is where the @Database is coded and thus Database_impl is the generated java to look at that has the create table SQL for the tables :-

enter image description here

Upvotes: 2

Related Questions