记得在build.gradle
添加 apply plugin: 'kotlin-kapt'
kapt "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor
androidTestImplementation "androidx.room:room-testing:$room_version"
建表语句可以直接复制AppDatabase_Impl.java
-> createAllTables
的。需要注意的就是改变了表结构之后重新Build
一下
注意Dao文件中@Transaction
的使用
当两个类的PrimaryKey
都叫id
时 join
表里又自定义了两个字段的id:如下:
@Entity
data class PersonSubjectJoin(
@ColumnInfo(name = "p_id")
val personId: Int,
@ColumnInfo(name = "s_id")
val subjectId: Int
)
这个时候定义PersonWithSubjects
或者 SubjectWithPerson
类的时候需要指定associateBy
的parentColumn
、entityColumn
,像下边这样:
data class PersonWithSubjects(
@Embedded val person: Person,
@Relation(
parentColumn = "id",
entityColumn = "id",
associateBy = Junction(
PersonSubjectJoin::class,
parentColumn = "p_id", //note
entityColumn = "s_id" //note
)
)
val subjects: List<Subject>
)
Migration测试 https://medium.com/androiddevelopers/testing-room-migrations-be93cdb0d975
//官方Simple中的Converter例子
public class DateConverter {
@TypeConverter
public static Date toDate(Long timestamp) {
return timestamp == null ? null : new Date(timestamp);
}
@TypeConverter
public static Long toTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}