Android Room:Order By 不工​​作 [英] Android Room: Order By not working

查看:55
本文介绍了Android Room:Order By 不工​​作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的 Android ORM Room.我遇到了以下问题,使用 ORDER BY 和参数的查询不起作用.

I am using the new Android ORM Room. And I faced the following issue, queries that use ORDER BY with arguments don't work.

如果我想使用从 ORDER BY 的参数填充的字段,它不起作用.它只是不排序任何东西.

If I want to use the field populated from a parameter for ORDER BY it does not work. It just doesn't sort anything.

@Query("SELECT * FROM User ORDER BY :orderBY ASC")
List<User> sortedFind(String orderBY);

但是,当我将 ORDER BY 列直接放在查询中以对结果进行排序时,它会按预期工作.

But, when I put the ORDER BY column directly in the query to sort the results, then it works as expected.

@Query("SELECT * FROM User ORDER BY name ASC")
List<User> sortedFind();

这是 Android Room 上的错误,还是我做错了什么?

Is it a bug on Android Room, or am I doing something wrong?

推荐答案

发生了什么

您可以作为参数传递给 @Dao 方法的唯一值是值,而不是查询字符串.这样做的原因(我相信)是为了防止 SQL 注入问题.

The only values you can pass as paramters to @Dao methods are values, not query strings. The reason for this (I beleive) is to prevent SQL injection issues.

为什么会这样

例如查询 SELECT * emails WHERE uid = ? 然后将值设置为 "1 OR WHERE isAdmin = true".这将允许人们在您的数据库上运行他们自己的定制查询并做他们想做的事.

For example the query SELECT * emails WHERE uid = ? then setting the value as "1 OR WHERE isAdmin = true". This would allow people to run their own bespoke queries on your database and do what they want.

我的解决方案

我也遇到了这个问题.这是我的 解决方案.

I ran into this problem as well. Here is a link to my solution.

我的解决方案有两部分.首先 DynamicQueryservice 根据输入生成查询字符串和值数组,然后运行原始查询并返回一个 Cursor.其次,一个 Cursor2POJO 映射器,这样我就不必为类一遍又一遍地写出游标映射,也不必引入潜在的维护问题.我只是在我的类中添加注释(与房间列名称匹配),其余的由 lib 处理.

My solution has 2 parts. First DynamicQueryservice that generates the query string and value array based on input, then runs the raw query and returns a Cursor. Second, a Cursor2POJO mapper so I do not have to write out cursor mappings over and over for classes, nor introduce potential maintenance issues. I just add annotations to my classes (that match up with room column names) and the lib handles the rest.

为了您的利益,我已将我的 Cursor 映射器分离到它自己的中,您可以随意使用它(如果自述文件不清楚,或者评论中有错误,就这样做了).

I've separated my Cursor mapper into its own library for your benefit, feel free to use it (just made it so if the readme is not clear, or there are bugs hit me up in the comments).

附言我的图书馆无法使用 Room @ColumnInfo 获取列名,因为注释当前设置为 RetentionPolicy.CLASS,因此无法通过反射访问.(添加到 Google 问题跟踪器 https://issuetracker.google.com/issues/63720940)

P.S. My library cannot use Room @ColumnInfo to get column names as the annotation is currently set as RetentionPolicy.CLASS so cannot be accessed through reflection. (added to Google issue tracker https://issuetracker.google.com/issues/63720940)

这篇关于Android Room:Order By 不工​​作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆