我有两个实体 帐户:
@Entity(tableName = "accounts",foreignKeys = arrayOf(
ForeignKey(
entity = Currency::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("currencyId"),
onDelete = ForeignKey.CASCADE
)
))
data class Account (
@PrimaryKey(autoGenerate = true)
var id:Int=0,
@ColumnInfo(name="name")
var accountName:String,
@ColumnInfo(name = "balance")
var initialBalance:Double,
var currencyId:Int,
var date:Date,
var isDefault:Boolean=true
){
constructor():this(0,"",0.0,0,Date(),false)
}
和货币:
@Entity(tableName = "currencies")
data class Currency(
@PrimaryKey(autoGenerate = true)
var id:Int=0,
@ColumnInfo(name="name")
var currencyName:String,
@ColumnInfo(name="code")
var currencyCode:String
)
{
constructor():this(0,"","")
override fun toString(): String =currencyCode
}
我想在account
中嵌入一个currency
对象。如您所见,我在 currencies
和 accounts
之间建立了一对多的关系。当我查询 accounts
实体时,我也想查看其货币。
我尝试在 account
实体中添加一个 @Embedded
字段,但它不起作用 显然我误解了什么,该字段被返回with null “没有异常(exception)只是null”。如果可能的话,将 account
对象中的 currency
对象“扁平化”,这会好得多。
所有这一切的重点是,我想在 RecyclerView
中显示所有帐户及其货币信息。我现在对 @Embedded
和 @Relation
感到困惑,非常感谢任何帮助。
编辑
我不知道这是否有帮助:
这是我的 AccountDao
:
@Dao
interface AccountDao {
@Insert
fun insertAll(items:Array<Account>)
@Update
fun update(item:Account)
@Delete
fun delete(item:Account)
@Query("select * from accounts")
fun getAll():LiveData<Array<Account>>
}
最佳答案
我不会推荐上述方法,因为您最终会编写相同的属性(重复自己),也就是样板代码。
使用 @Embedded和 Relation以下列方式注释,您的代码很可能如下所示:
data class AccountWithCurrency (
@Embedded
var account: Account? = null,
@Relation(parentColumn = "id", entityColumn = "currencyId")
var currency: List<Currency>? = null,
){
constructor() : this(Account(), emptyList())
}
关于Android Room Kotlin 内部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49305683/