@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.
本文介绍Room持久化库的@Query注解用法,包括绑定参数、列表参数支持、查询类型及返回类型等内容。同时探讨了如何使用RxJava2进行响应式编程。

292

被折叠的 条评论
为什么被折叠?



