【Android】【初心者向け】 RoomのAutoIncrement(PrimaryKeyのautogenerate = true)の値は、0で良い
概要
タイトル通りですが、AndroidのRoomのAutoincrement(PrimaryKeyのautogenerate = true)の値は、0で良いという話です。
今まで、業務でRoomを使う経験がなく、 ドキュメントやサンプルコードを見ていて、
AutoIncrementのときに、何を渡せば良いのかわからず、どこかで見たサンプルと同じように0
を渡しすようにしていました。
ただふとこれで正しいのかと気になり、調べてみて良かったということに気づいたという話です。
参考にしたもの
developers: Primarykey
以下は、引用です。
autoGenerate
public boolean autoGenerate ()
Set to true to let SQLite generate the unique id.
When set to true, the SQLite type affinity for the field should be INTEGER.
If the field type is long or int (or its TypeConverter converts it to a long or int), Insert methods treat 0 as not-set while inserting the item.
If the field's type is Integer or Long (or its TypeConverter converts it to an Integer or a Long), Insert methods treat null as not-set while inserting the item.
つまり、以下のような内容かと思います。
- autoGenerateをtrueにすると、SQLiteがユニークなIDを生成するよ
- 型が
long
かint
のときは、insertのメソッドは、0を未設定として扱うよ - 型が、
Long
かInteger
のときは、insertのメソッドは、nullを未設定として扱うよ
そして、基本的にはkotlinのint
を使うかと思いますので、0を設定してあげるのが良いということになるかと思います。
コード的なイメージ
仮にUserというEntityを使う場合ですが、以下のようになるのかと思います。
UserEntity.kt
@Entity(tableName = "users")
data class User(
// デフォルト引数に0を設定
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name ="name") val name: String
)