问题
I have these classes:
@Entity
public class Person {
long id;
String name;
}
@Entity
public class Dog {
long id;
String color;
long idPerson;
}
public class PersonWithDog {
@Embedded
Person person;
@Relation(parentColumn = "id", entityColumn = "idPerson", entity = Dog.class)
List<Dog> dogs;
}
I want to make a query to return a person and a list of only black dogs he owns. Something like:
SELECT * FROM Person
LEFT JOIN Dogs ON Person.id = Dogs.idPerson
WHERE Person.id = ? AND Dogs.color = black
Is this possible using Room?
**Note: If I make a POJO this way:
public class PersonWithDog {
@Embedded
Person person;
@Embedded
List<Dog> dogs;
}
and use the above query, Room won't find out how to map the fields of List, as it doesn't accept an embedded list...
回答1:
If nothing else worked, this dirty solution may help you as a last resort. Note that the return type could not be LiveData
and you should call the method every time you need the data (and perhaps wrap its result in a SingleLiveEvent or something):
@Dao
public abstract class MyDao {
// Call this method
@Transaction
Map<Person, List<Dog>> getPersonBlackDogs(long personId) {
Person person = getPerson(personId);
List<Dog> blackDogs = getBlackDogs(personId);
return Collections.singletonMap(person, blackDogs);
}
// You do not want to expose these two methods so make theme protected
@Query("SELECT * FROM Person WHERE id = :personId")
protected abstract Person getPerson(long personId);
@Query("SELECT * FROM Dog WHERE idPerson = :personId AND Dog.color = black")
protected abstract List<Dog> getBlackDogs(long personId);
}
来源:https://stackoverflow.com/questions/56028379/room-sql-query-object-with-relation-1-to-many-using-where-parameters-on-both-ta