I have two entities Accounts:
@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)
}
And Currencies:
@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
}
I want to embed a currency object in account. As you can see, I have one-to-many relationship between currencies and accounts. When I query the accounts entity I want to view its currency too.
I tried adding an @Embedded field in account entity but it doesn't work obviously there is something I'm misunderstanding , the field is returned with null "No exception just null". And if possible to "flatten" the currency object inside the account object, this would be much better.
The point of all of this is, I want to display all accounts in RecyclerView with their currencies information. I'm now confused between @Embedded and @Relation any help would be much appreciated.
Edit
I don't know if this might help:
This is my 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>>
}
I won't recommend the above method because you end up writing the same properties (repeating yourself) aka boilerplate code.
Use the @Embedded and Relation annotation in the following way and your code will most probably look like this:
data class AccountWithCurrency (
@Embedded
var account: Account? = null,
@Relation(parentColumn = "id", entityColumn = "currencyId")
var currency: List<Currency>? = null,
){
constructor() : this(Account(), emptyList())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With