Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enum on WHERE clause inside a @Query - Android Room

Since Android Room 2.3.0 we can use enum fields on our @Entity classes without having to write an @TypeConverter for it. But how to use those values inside an @Query?

Let's say that we need to list all the "approved" items:

@Entity(tableName = "items")
public class Item {
    //...
    public Status status;
    //...
}

public enum Status {
    APPROVED,
    DENIED
}

@Dao
public interface ItemDao {
   //...
    @Query("SELECT * FROM items WHERE status = ???????")
    List<Item> getAllApprovedItems();
   //...
}

Of course that I can set a value to my enum, and create a type converter for it, like this:

APPROVED(1),
DENIED(2)

and then make a query

@Query("SELECT * FROM items WHERE status = 1")

But I think this is prone to errors.

Is there a way to use the enum values inside the @Query? And more importantly, that the value would be evaluated on compile-time?

like image 203
Ar1sartori Avatar asked Oct 19 '25 09:10

Ar1sartori


1 Answers

If you use Database Inspector to look into the data in your database, you will find that the enum is stored in DB by the name string APPROVED and DENIED. So you can write the query like this

@Query("SELECT * FROM items WHERE status = 'APPROVED'")

like image 134
Tink Avatar answered Oct 21 '25 23:10

Tink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!