I am migrating an app to use Room
from normal Sqlite
and one part that I am having trouble with is that there are several queries that have an orde
As tyczj already suggested you can us a RawQuery
. In addition, the SimpleSQLiteQuery
can also be moved into the DAO so there are no SQL statements outside of the DAO.
A DAO can also be defined via an abstract class. This allows you to add a method which executes the SimpleSQLiteQuery
.
Example:
@DAO
public abstract class UserDao {
@RawQuery
public abstract List getUsersViaRawQuery(SupportSQLiteQuery query);
public List getUsersOrderBy(String column) {
String statement = "SELECT * FROM user ORDER BY " + column + " ASC";
SupportSQLiteQuery query = new SimpleSQLiteQuery(statement, new Object[]{});
return getUsersViaRawQuery(query);
}
}
The column parameter could also be replaced by an enum, which only allows specific values.
Example:
private static String createOrderByString(Order order) {
switch (order) {
case NAME:
return "ORDER BY first_name ASC, last_name ASC";
case AGE:
return "ORDER BY age DESC";
default:
return "";
}
}