【学习笔记】Room的使用


@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对象。 对于返回多个值的查询,可以使用ListArray。 除此之外,任何查询都可以返回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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值