通过主键查询实体不使用房间
我正在尝试通过ID从我的房间数据库中查询实体,而不会成功。在这里,我的数据库:
实体:
@Entity(tableName = "artist")
data class Artist(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val name: String,
)
呼吸:
@Singleton
class AppRepository @Inject constructor(
private val artistDao: ArtistDao
) {
suspend fun insert(artist: Artist) {
artistDao.insert(artist)
}
fun getArtist(id: Long) = artistDao.getArtist(id)
}
dao:
@Query("SELECT * FROM artist WHERE id = :id")
fun getArtist(id: Long): Flow<Day>
viewModel:
@HiltViewModel
class ArtistViewModel @Inject constructor(
private val repository: AppRepository,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private val artistId: Long =
savedStateHandle.get(ARTIST_ID_SAVED_STATE_KEY) ?: 0
fun insert(artist: Artist) = viewModelScope.launch {
repository.insert(artist)
}
val artist =
repository.getArtist(artistId).distinctUntilChanged().asLiveData()
}
从viewmodel
返回始终为null。另一方面,当我使用name
Artist
实体的字段做同样的事情时,我会得到一些值。 我想知道在由主钥匙查询时是否还有其他事情要注意。
I am trying to query entities from my room database by id without success. Here my database:
Entity:
@Entity(tableName = "artist")
data class Artist(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val name: String,
)
Respository:
@Singleton
class AppRepository @Inject constructor(
private val artistDao: ArtistDao
) {
suspend fun insert(artist: Artist) {
artistDao.insert(artist)
}
fun getArtist(id: Long) = artistDao.getArtist(id)
}
Dao:
@Query("SELECT * FROM artist WHERE id = :id")
fun getArtist(id: Long): Flow<Day>
ViewModel:
@HiltViewModel
class ArtistViewModel @Inject constructor(
private val repository: AppRepository,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private val artistId: Long =
savedStateHandle.get(ARTIST_ID_SAVED_STATE_KEY) ?: 0
fun insert(artist: Artist) = viewModelScope.launch {
repository.insert(artist)
}
val artist =
repository.getArtist(artistId).distinctUntilChanged().asLiveData()
}
Observing the artist field from viewModel
returns always null. On the other hand when I do the same thing using the name
field of the Artist
entity I get some value.
I'm wondering if there are some other things to pay attention when querying by the primary key.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两件事:
首先 - 您将其插入数据库中:
但切勿更改
SavedStateHandle
。第二。
Artist
不会更改,因为您可以在ArtistID
为0*和Artist
对更改的更改中没有反应ArtistId
。There are two things:
First - You insert it into the database:
but never changing the
savedStateHandle
.Second. The
artist
won't change because you initialize it at view model creation whereartistId
is 0* andartist
has no reaction on the change of theartistId
.