Mah*_*oud 6 android kotlin android-room
我有两个实体帐户:
@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)
}
Run Code Online (Sandbox Code Playgroud)
和货币:
@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
}
Run Code Online (Sandbox Code Playgroud)
我想在中嵌入一个currency对象account。如您所见,currencies和之间存在一对多关系accounts。当我查询accounts实体时,我也想查看其货币。我尝试@Embedded在account实体中添加一个字段,但显然无法正常工作,这是我误解了,该字段返回null,“ No exception just null”。而且,如果可以将currency对象“扁平化”到对象内部account,效果会更好。
所有这些的重点是,我想显示所有帐户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>>
}
Run Code Online (Sandbox Code Playgroud)
我设法让它发挥作用。解决方案是创建一个单独的(POJO 或 POKO 等)类,我将其命名为AccountModel:
class AccountModel{
var accountId:Int = 0
var accountName:String = ""
var accountInitialBalance:Double = 0.0
var accountCreationDate: Date = Date()
var currencyId:Int = 0
var currencyCode:String = ""
var isDefaultAccount:Boolean = false
constructor()
constructor(id:Int,name:String,balance:Double,date:Date,currencyId:Int,currencyCode:String,isDefault:Boolean){
this.accountId = id
this.accountName = name
this.accountInitialBalance = balance
this.accountCreationDate = date
this.currencyId = currencyId
this.currencyCode = currencyCode
this.isDefaultAccount= isDefault
}
fun toAccount():Account = Account(this.accountId,this.accountName,this.accountInitialBalance,this.currencyId,this.accountCreationDate,this.isDefaultAccount)
}
Run Code Online (Sandbox Code Playgroud)
然后,构建查询以执行正常操作,就像对普通 SQL 数据库inner join执行的操作一样。inner join像这样:
@Query("select accounts.id as accountId," +
"accounts.name as accountName," +
"accounts.balance as accountInitialBalance," +
"accounts.currencyId," +
"accounts.date as accountCreationDate," +
"accounts.isDefault as isDefaultAccount," +
"currencies.code as currencyCode " +
"from accounts inner join currencies on accounts.currencyId=currencies.id")
fun getAll():LiveData<Array<AccountModel>>
Run Code Online (Sandbox Code Playgroud)
显然,您可以使用as x将此列投影到x返回对象中的字段,正如您所知,在数据库中该列是,accounts.id但在我的中AccountModel它是一个accountId. Google Room 真正令人印象深刻的是,即使我添加了一个非常聪明的对象,
我也能得到一个LiveData。AccountModelAccount