房间:如何基于复合主键进行查询?

问题描述 投票:0回答:1

Room 可以使用复合主键进行查询吗?

@Entity(
    tableName = "market_cap",
    primaryKeys = ["assetId", "timestamp"]
)
data class MarketCapDataEntity(
    val assetId: String,
    val timestamp: Long,
    val price: Double
)

假设我想按主键执行查询,如下所示?

@Query("SELECT * FROM market_cap WHERE primaryKeys = :compositeKey")
suspend fun getMarketCapByAssetId(compositeKey: String): List<MarketCapDataEntity>
android sqlite android-sqlite android-room
1个回答
0
投票

您需要在 SQL 查询中指定主键的每个组成部分,而不是尝试使用单个组合键

@Entity(
    tableName = "market_cap",
    primaryKeys = ["assetId", "timestamp"]
)
data class MarketCapDataEntity(
    val assetId: String,
    val timestamp: Long,
    val price: Double
)

@Dao
interface MarketCapDao {
    @Query("SELECT * FROM market_cap WHERE assetId = :assetId AND timestamp = :timestamp")
    suspend fun getMarketCapByAssetIdAndTimestamp(assetId: String, timestamp: Long): MarketCapDataEntity?
}
© www.soinside.com 2019 - 2024. All rights reserved.