【问题标题】:Room SQL: Query object with relation 1-to-Many using WHERE parameters on both tablesRoom SQL:使用两个表上的 WHERE 参数查询具有一对多关系的对象
【发布时间】:2019-05-07 18:15:48
【问题描述】:

我有这些课程:

@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

这可以使用 Room 吗?

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

public class PersonWithDog {
    @Embedded
    Person person;

    @Embedded
    List<Dog> dogs;
}

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

【问题讨论】:

  • 看看this question
  • 这个问题的答案似乎不起作用......我不能@Embedded a List。如果我使用连接查询执行此操作,我会收到错误“查询返回一些不被...使用的列 [...]”

标签: java android android-room


【解决方案1】:

如果没有其他办法,这个肮脏的解决方案可能会作为最后的手段帮助你。请注意,返回类型不能是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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多