首页 > 解决方案 > Room SQL:使用两个表上的 WHERE 参数查询具有一对多关系的对象

问题描述

我有这些课程:

@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;
}

我想进行查询以返回一个人和他拥有的唯一黑狗的列表。就像是:

SELECT * FROM Person 
LEFT JOIN Dogs ON Person.id = Dogs.idPerson 
WHERE Person.id = ? AND Dogs.color = black

这可以使用房间吗?

**注意:如果我以这种方式制作 POJO:

public class PersonWithDog {
    @Embedded
    Person person;

    @Embedded
    List<Dog> dogs;
}

并使用上面的查询,Room 不会知道如何映射 List 的字段,因为它不接受嵌入式列表......

标签: javaandroidandroid-room

解决方案


如果没有其他方法,这个肮脏的解决方案可能会帮助你作为最后的手段。请注意,返回类型不能是LiveData,您应该在每次需要数据时调用该方法(并且可能将其结果包装在SingleLiveEvent或其他东西中):

@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);
}

推荐阅读