使用@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 (
和其他一些逻辑,似乎没有办法修改生成的子查询。
如果其中一位Room开发人员正在阅读本文,谢谢,我讨厌。
还有另一种方法吗?
答案 0 :(得分:1)
通过@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
@Dao
public interface PostWithCommentsDao {
@Query("SELECT * FROM post")
List<PostWithComments> getPostWithComments();
}
您还需要更新扩展RoomDatabase的数据库类,并且可能需要更新版本。
@Database(entities = {Post.class, Comment.class}, views = {ApprovedComment.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase
答案 1 :(得分:0)
未经测试,但是您可以尝试...
public class PostWithComments {
@Embedded
public Post post;
@Embedded
public Comment comment;
}
@Dao
public interface PostWithCommentsDao {
@Query("SELECT post.*, comment.* FROM post LEFT JOIN comment ON post.id=comment.post_id where comment.status = 'approved'")
List<PostWithComments> getPostWithComments();
}