@Query
注解
Room
仅支持被命名的绑定参数:name
来避免方法参数和query绑定参数之间的混淆。
Room will automatically bind the parameters of the method into the bind arguments. This is done by matching the name of the parameters to the name of the bind arguments.
@Query("SELECT * FROM user WHERE user_name LIKE :name AND last_name LIKE :last")
public abstract List<User> findUsersByNameAndLastName(String name, String last);
作为SQLite绑定参数的扩展,Room支持绑定list参数到query
中。
如上所示,如果userIds
是有3个元素的数组,Room
会执行如下query
:
SELECT * FROM user WHERE uid IN(?, ?, ?)
并将userIds
中的每个item绑定到语句中。
Query
方法支持3种查询类型:SELECT
, UPDATE
and DELETE
.
对于SELECT
查询,Room会根据方法的返回类型推断出结果内容,并生成将自动将查询结果转换为方法的返回类型的代码。 对于单个结果查询,返回类型可以是任何java对象。 对于返回多个值的查询,可以使用List
或Array
。 除此之外,任何查询都可以返回Cursor
,或者可以将任何查询结果包装到LiveData
中。
如果你使用RxJava2
,你也可以从查询方法中返回Flowable<T>
or Publisher<T>。
由于Reactive Stream
不允许为null
,如果查询返回一个nullable
类型,it will not dispatch anything if the value is null(例如获取不存在的Entity row). 你可以返回Flowable <T []>
或Flowable <List <T >>
来解决此限制。
Both Flowable<T>
and Publisher<T>
will observe the database for changes and re-dispatch if data changes. If you want to query the database without observing changes, you can use Maybe<T>
or Single<T>
. If a Single<T>
query returns null
, Room will throw EmptyResultSetException.
UPDATE
or DELETE
queries can return void
or int
. If it is an int
, the value is 查询的行数。
You can return arbitrary POJOs
from your query methods as long as the fields of the POJO
match the column names in the query result. For example, if you have class:
class UserName {
public String name;
@ColumnInfo(name = "last_name")
public String lastName;
}
You can write a query
like this:
@Query("SELECT last_name, name FROM user WHERE uid = :userId LIMIT 1")
public abstract UserName findOneUserName(int userId);
更多关于Room和RxJava2的,请看文章Room&RxJava.