Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room DAO Order By ASC or DESC variable

I'm trying to make a @Query function in my @Dao interface which has a boolean parameter, isAsc to determine the order:

@Query("SELECT * FROM Persons ORDER BY first_name (:isAsc ? ASC : DESC)")
List<Person> getPersonsAlphabetically(boolean isAsc);

Apparently this isn't allowed. Is there a work around here?

EDIT:

It seemed odd to use two queries (below) since the only difference is ASC and DESC:

@Query("SELECT * FROM Persons ORDER BY last_name ASC")
List<Person> getPersonsSortByAscLastName();

@Query("SELECT * FROM Persons ORDER BY last_name DESC")
List<Person> getPersonsSortByDescLastName();
like image 310
aLL Avatar asked Mar 22 '19 10:03

aLL


People also ask

What is DAO in room database?

When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.

Is Room A ORM?

Is Android Room an ORM? Room isn't an ORM; instead, it is a whole library that allows us to create and manipulate SQLite databases more easily. By using annotations, we can define our databases, tables, and operations.

How does room database work?

Room autogenerates implementations of your @Database and @Dao annotated classes the first time you compile your code after creating a Room Database. The implementation of UserDatabase and UserDao in the preceding example is generated automatically by the Room annotation processor.

What is DAO in android?

Data Access Objects are the main classes where you define your database interactions. They can include a variety of query methods. The class marked with @Dao should either be an interface or an abstract class.


2 Answers

Use CASE Expression for SQLite to achieve this in Room DAO,

@Query("SELECT * FROM Persons ORDER BY 
        CASE WHEN :isAsc = 1 THEN first_name END ASC, 
        CASE WHEN :isAsc = 0 THEN first_name END DESC")
List<Person> getPersonsAlphabetically(boolean isAsc);
like image 172
Chandan Sharma Avatar answered Oct 07 '22 20:10

Chandan Sharma


Create two queries, one with ASC and one with DESC.

@Query("SELECT * FROM Persons ORDER BY last_name ASC")
List<Person> getPersonsSortByAscLastName();

@Query("SELECT * FROM Persons ORDER BY last_name DESC")
List<Person> getPersonsSortByDescLastName();
like image 34
just Avatar answered Oct 07 '22 21:10

just