Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to instantiate an Android Room Entity object for insertion without specifying the autogenerated PK? (Kotlin)

In Android, when using the Room database and using an auto-generated primary key, your pk will be a field of the object and therefore will need to be set when you create a plain-old Kotlin object. So what is a correct and clean way to instantiate an object that you use for insertion?

Say you have a table like so:

@Entity(tableName = "data")
class Data(
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Long,
    @ColumnInfo(name = "some_data") val someData: Int
)

If you want to actually insert a Data object, you will need to specify the id at initialization.

I see two possibilities, and am unsure if either are correct:

  • Assign it a dummy value. Will Room generate a real one for you when it actually inserts it into the database?
  • Change the field type to be Int? and always set its value to null.
like image 604
inappropriately optimized Avatar asked Oct 24 '25 15:10

inappropriately optimized


2 Answers

This worked for me:

@Entity(tableName = "data")
class Data(
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Long = 0,
    @ColumnInfo(name = "some_data") val someData: Int
)


fun generateData(name: String): Data {
    return Data(name=name)
}
like image 63
Denis Korobitsin Avatar answered Oct 27 '25 04:10

Denis Korobitsin


If within a Dao have :-

@Insert
fun insertDataRow(data: Data): Long
  • Thus the id of the inserted row will be returned

and then use

insertedId = myMado.insertDataRow(0,10)

The insertedId will be the generated id.

If you use Int? then you could use

insertedId = myMado.insertDataRow(null,10)

If with Int? if you used (with no existing data)

insertedId = myMado.insertDataRow(0,10)
insertedId = myMado.insertDataRow(0,11)

The you would get a UNIQUE constraint exception for the second insert as the id is set to 0.

That is there is a subtle change if you use Int? as opposed to Int. Int effectively treats 0 as null whilst the Int? treats 0 as the value 0

  • P.S. ideally you should use Long or Long? for the id as it can be a 64bit signed integer.
like image 41
MikeT Avatar answered Oct 27 '25 05:10

MikeT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!