简体   繁体   English

Android Room数据库视图

[英]Android Room database view

in android docs code for creating view in room database is 在Android文档代码中用于在房间数据库中创建视图是

@DatabaseView("SELECT user.id, user.name, user.departmentId," +
    "department.name AS departmentName FROM user " +
    "INNER JOIN department ON user.departmentId = department.id")
data class UserDetail(
var id: Long,
var name: String?,
var departmentId: Long,
var departmentName: String?
)

but how i can create view with some dynamic condition like user.id=userId where userId=1 or 2 or some integer 但是我如何创建具有诸如user.id = userId的动态条件的视图,其中userId = 1或2或某个整数

You can have Where clause in the query when creating a database view, but this will not be dynamic. 创建数据库视图时,可以在查询中包含Where子句,但这不是动态的。 Let's say you want to have a database view that only returns active users that are assigned to any department, so you could have Where user.active = true or something like that. 假设您要拥有一个仅返回分配给任何部门的活动用户的数据库视图,因此您可以使用Where user.active = true或类似的内容。 But this will be set on the schema, so everytime you query this view, it will only return active users. 但这将在模式上设置,因此,每次查询该视图时,它只会返回活动用户。

When adding a new user to the User table, the view will be automatically updated. 将新用户添加到“用户”表时,该视图将自动更新。

But you don't need to have this Where clause when creating the database view. 但是,在创建数据库视图时,不需要此Where子句。 Once the view is created, you can use as a normal table, so you can have a DAO that queries only the users that have the desired id. 创建视图后,您可以将其用作普通表,因此可以拥有仅查询具有所需ID的用户的DAO。

For example: 例如:

@Query("SELECT * FROM UserDetail WHERE id = :id")
fun search(id: Int): List<UserDetail>

So your view is a "table" that joins user and department and then you can query as a normal table and have filters. 因此,您的视图是连接用户和部门的“表”,然后您可以作为普通表进行查询并具有过滤器。

Does this help? 这有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM