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”表中有任何更改,则会发出对象

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...