Room SQL:在两个表上都使用WHERE参数来查询具有一对多关系的对象 [英] Room SQL: Query object with relation 1-to-Many using WHERE parameters on both tables

查看:82
本文介绍了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;
}

我想查询一个人并返回他拥有的只黑狗的列表.像这样:

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

使用Room可以吗?

**注意:如果我这样制作POJO:

**Note: If I make a POJO this way:

public class PersonWithDog {
    @Embedded
    Person person;

    @Embedded
    List<Dog> dogs;
}

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

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...

推荐答案

如果没有其他效果,此肮脏的解决方法可能会在最后帮助您.请注意,返回类型不能为 LiveData ,并且每次需要数据时都应调用该方法(并且可能将其结果包装在

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

这篇关于Room SQL:在两个表上都使用WHERE参数来查询具有一对多关系的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆