java - 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 的字段,因为它不接受嵌入式列表......
解决方案
如果没有其他方法,这个肮脏的解决方案可能会帮助你作为最后的手段。请注意,返回类型不能是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);
}
推荐阅读
- typescript - typeorm 如何使用存储库查询()方法填充实体
- caching - 使用带有缓存控制标头的 Go 服务器显式指定 FileServer 使用磁盘缓存而不是内存缓存?
- r - If else in ggplot +在geom_vline的字符和数字之间切换值
- java - 为什么 Amplify 强制使用身份池进行联合登录?
- r - 想使用 R 创建字符时间的条件间隔
- json - 如何减小此 JSON 记录的大小?
- python-3.x - 如何下载发送到电报机器人的.mp3文件并使用python将其转换为文本
- java - 我需要一个正则表达式来使用 java 进行名称验证
- python - asyncio call_soon 和 call_soon_threadsafe 的区别?为什么 call_soon 线程不安全?
- flutter - 颤振颤振_inappwebview“onEnterFullscreen”