android – 具有一对一关系的房间数据库

前端之家收集整理的这篇文章主要介绍了android – 具有一对一关系的房间数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有2个实体,硬币和CoinRevenue.

基本上,硬币以其他货币持有美元价格.

例如,带符号EUR的硬币,值为1.0356

@Entity(tableName = "coin")
data class Coin(
        @field:PrimaryKey(autoGenerate = false)
        var id: String = "",var symbol: String = "",var pricInUsd: Float = 0f)

CoinRevenue是一个实体,我用它来保存用户拥有的特定硬币的硬币数量.
例如,CoinRevenue与Coin Entity有关,EUR符号和金额为1000.

@Entity(tableName = "coinRevenue")
    data class CoinRevenueNew(
            @field:PrimaryKey(autoGenerate = true)
            var id: Int = 0,var coin: Coin? = null,var amount: Float = 0f)

现在我想从数据库获取CoinRevenue并从数据库获取更新的Coin.

例如,我用(EUR,1.0253)保存了硬币
而且用这枚硬币保存了一枚CoinRevenue.

之后我更新了硬币(EUR,2.522)
我希望CoinRevenue中的Coin对象也会更新.

我知道@Embedded只是将内部objet字段作为列添加到同一个父对象.
当我使用关系时,我必须使用List或Set.
但我在CoinRevenue里总是有1枚硬币.

我的硬币DA:

@Query("select * from coin order by rank")
fun getAllCoins(): Flowable<List<CoinDB>>

@Query("select * from coin where rank = 1")
fun getFirstCoin(): Maybe<CoinDB>

@Query("select * from coin where favourite = 1 order by rank")
fun getAllFavouriteCoins(): Flowable<List<CoinDB>>

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertCoin(coinDB: CoinDB)

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertCoins(coinsList: List<CoinDB>)

// -----------------
// CoinRevenue
// -----------------

@Query("select * from coinRevenue order by rank")
fun getAllCoinsRevenue(): Flowable<List<CoinRevenue>>

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertCoinRevenue(coinRevenue: CoinRevenue)

@Delete()
fun deleteCoinRevenue(coinRevenue: CoinRevenue)

创造这个的最好方法是什么?

解决方法

所以经过多次尝试,我已经设法让它发挥作用.

我更改了CoinRevenue对象以保存Coin id的外键

@Entity(tableName = "coinRevenue",foreignKeys = (arrayOf(ForeignKey(
        entity = CoinDB::class,onUpdate = ForeignKey.CASCADE,parentColumns = arrayOf("coinId"),childColumns = arrayOf("coinDbId"))))
)
data class CoinRevenue(
        @ColumnInfo(name = "mid")
        @PrimaryKey(autoGenerate = true)
        var id: Long = 0L,@ColumnInfo(name = "coinDbId")
        var coinDbId: String? = null,@ColumnInfo(name = "amount")
        var amount: Double = 0.toDouble()
)

我需要用两个对象创建一个POJO,如下所示:

class CoinRevenueWithCoin() : Parcelable {
@Embedded lateinit var coinDB: CoinDB
@Embedded lateinit var coinRevenue: CoinRevenue
}

和这样的查询

@Query("select * from coinRevenue,coin where coinRevenue.coinDbId = coin.coinId order by coin.rank")
fun getAllCoinsRevenueWithCoin(): Flowable<List<CoinRevenueWithCoin>>

而已.

此外,此查询与任何其他常规对象查询一样,如果“coin”表或“coinRevenue”表中有任何更改,则会发出对象

原文链接:https://www.f2er.com/android/309969.html

猜你在找的Android相关文章