Hi! Thanks :)
I’m not sure if I understood your question properly, but if you want to have Coin
field in your CoinRevenue
object and this is one-to-one relationship, then I think the best way is to use @Embedded
annotation like this:
@Entity(tableName = "coinRevenue")
data class CoinRevenue(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
@Embedded(prefix = "coin_")
var coin: Coin,
var amount: Float = 0f)
You need to add prefix
, because both Coin
and CoinRevenue
data classes have fields with the same name (id
). Thanks to @Embedded
annotation table for CoinRevenue will have fields: id
, coin_id
, coin_symbol
, coin_priceInUsd
, amount
— so it’s all in one table, but you have two separate classes.
Also, to make @Embedded
work, you need to remove @Entity
annotation from Coin
class:
data class Coin(
var id: Int = 0,
var symbol: String? = null,
var priceInUsd: Float = 0f)
You need to do it, because you (probably) don’t want to have two tables with Coins
(one from Coin
class and second from embedded field in CoinRevenue
). Thanks to this when you want to update e.g. priceInUsd
you can do it like this:
val coin = Coin(1, "EUR", 1.0253f)
val coinRevenue = CoinRevenue(1, coin, 1000f)// if you want to update price of coin:
coin.priceInUsd = 2.522f
coinDao.updateCoinRevenue(coinRevenue)
Hope it’ll help you!