简体   繁体   中英

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?

You can easily use it like any type and room will deal with it as a string values

@Query("SELECT * FROM items WHERE status = :status")
Item getAllApprovedItems(Status status);

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'")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM