首页 > 解决方案 > 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 (和其他一些逻辑,似乎没有办法修改生成的子查询。

还有另一种方法可以做到这一点吗?

标签: androidandroid-roomandroid-architecture-components

解决方案


使用@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

推荐阅读