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();
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 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.
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.
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.
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);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With