android - Room 使用 @Relation 注解 - 一对多关系 where 子句子关系
问题描述
使用@Relation 注释。我可以使用以下方法查询一对多关系:
@Dao
public interface PostDao {
@Query("SELECT * FROM post")
List<PostWithComments> getPostWithComments();
}
这里是实体
@Entity
public class Post {
@PrimrayKey
private int id;
private String title;
private String content;
}
@Entity
public class Comment {
@PrimrayKey
private int id;
private int post_id;
private String content;
private String status;
}
public class PostWithComments {
@Embedded
public Post post;
@Relation(parentColumn = "id", entityColumn = "post_id", entity = Comment.class)
public List<Comment> comments;
}
我想得到所有有评论的帖子,status = approved
但我不确定房间如何处理这个问题。我尝试了以下方法:
@Dao
public interface PostDao {
@Query("SELECT * FROM post INNER JOIN comment ON post.id = comment.post_id WHERE comment.status = 'approved'")
List<PostWithComments> getPostWithComments();
}
我在结果中有重复。List<PostWithComments>
每个帖子在结果中有多次。
更新:
在阅读生成的代码后PostDao_Impl.java
,Room 似乎正在执行子查询来获取关系。
首先,它@Query
从方法执行注解中的查询getPostWithComments
,然后生成要填充的关系的子查询List<Comment>
SELECT id, post_id, title, content FROM comment WHERE post_id IN (
和其他一些逻辑,似乎没有办法修改生成的子查询。
还有另一种方法可以做到这一点吗?
解决方案
使用@Relation,您可以使用@DatabaseView
@DatabaseView("SELECT * FROM comments WHERE status = 'approved'")
public class ApprovedComment {
@Embedded
Comment comment;
}
PostWithComments 类
public class PostWithComments {
@Embedded
public Post post;
@Relation(parentColumn = "id", entityColumn = "post_id", entity = ApprovedComment.class)
public List<ApprovedComment> comments;
}
道
@Dao
public interface PostWithCommentsDao {
@Query("SELECT * FROM post")
List<PostWithComments> getPostWithComments();
}
您还需要更新扩展 RoomDatabase 的 Database 类,并且可能需要更新版本。
@Database(entities = {Post.class, Comment.class}, views = {ApprovedComment.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase
推荐阅读
- python - 我试图以 100hz 采样,而不是像程序运行一样快。我该怎么做?
- django - 如何从 Django 模型表单中的 POST 请求中提取单个值?
- python - 如何根据时间不在列表中的时间戳删除行
- cron - Cron schedule to run at 11:55, 12:00 and 12:05
- angular - 在Angular 6中只允许只有一位小数的正数
- python - 在 Python 中的任何文件或目录中重命名部分名称
- zooming - 如何调整打开图层的缩放以查看地图上的所有 POI 和标记
- c# - 极其简单的线性搜索不适用于 Android 和 iOS
- vuejs2 - 在组件属性中使用 Lang.js
- elasticsearch - 限制聚合处理的结果数量