Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a table with two WHERE clauses efficiently (Android Room)

Supposed I have an object

class Person {
    String firstName;
    String lastName;
    ... other fields...
}

and a database that contains

@Entity
class DatabaseTable {
    String firstName;
    String lastName;
    ... other unrelated fields from person...
}

now in my Dao, I have

@Query("SELECT * FROM DatabaseTable WHERE " +
        " firstName = :firstName AND lastName = :lastName")
List<DatabaseTable> getAll(String firstName, String lastName);

I have list that I want to query DatabaseTable from.

Person("Apple", "Kohn", ...)
Person("Benny", "Lorie", ...)
Person("Cindy", "May", ...)
... 

How would i go about extracting the Database table efficiently? It don't seem right to call the dao for every Person in my list.

EDIT:

I like to know how to use a single query to retrieve a list of results.

I know that under the hood Room uses ContentValue to loop though an entity list. Is there a way for us to create our own contentValue to pass into Room?

Is something like the following possible?

getAllWithPairs( List<String> firstNames, List<String> lastNames);
like image 524
Angel Koh Avatar asked Oct 30 '17 03:10

Angel Koh


2 Answers

By adding AND after your first part of the WHERE statement you can append additional WHERE logic.

Sample

@Query("SELECT * FROM content WHERE timestamp >= :timeframe AND feedType = :feedType ORDER BY qualityScore DESC")
fun getMainContent(timeframe: Date, feedType: FeedType): DataSource.Factory<Int, Content>
like image 137
Adam Hurwitz Avatar answered Nov 18 '22 07:11

Adam Hurwitz


If I understood your question correctly you are calling the

List<DatabaseTable> getAll(String firstName, String lastName);

for every person in your database one at a time. I think what you are looking for is:

@Query("SELECT * FROM DatabaseTable")
List<DatabaseTable> getAll();

This should get you every person the the table - DatabaseTable

For the edit part of the question try this:

@Query("SELECT * FROM DatabaseTable WHERE 
    firstName IN (:firstNames) AND secondName IN (:lastNames)")
getAllWithPairs(List<String> firstNames, List<String> lastNames);
like image 23
N1234 Avatar answered Nov 18 '22 08:11

N1234