Room 使用@Relation 注解——一对多关系 where 子句子关系

Room using the @Relation annotation - one to many relationship where clause child relationship

使用@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 发表评论的 post,但我不确定 room 如何处理这个问题。我尝试了以下方法:

 @Dao
 public interface PostDao {
        @Query("SELECT * FROM post INNER JOIN comment ON post.id = comment.post_id WHERE comment.status = 'approved'")
        List<PostWithComments> getPostWithComments();
 }

我得到了重复的结果。每个 post 在 List<PostWithComments> 结果中出现多次。

更新:

阅读 PostDao_Impl.java 处生成的代码后,Room 似乎正在执行子查询以获取关系。

首先,它从 getPostWithComments 方法执行 @Query 注释中的查询,然后它为关系生成一个子查询以填充 List<Comment>

SELECT id, post_id, title, content FROM comment WHERE post_id IN ( 和其他一些逻辑,似乎没有办法修改生成的子查询。

还有其他方法吗?

未测试,但您可以试试这个...

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

有了@Relation,你可以使用@DatabaseView

@DatabaseView("SELECT * FROM comments WHERE status = 'approved'")
public class ApprovedComment {
  @Embedded
  Comment comment;
}

PostWithComments class

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 的数据库 class,您可能需要更新版本。

@Database(entities = {Post.class, Comment.class}, views = {ApprovedComment.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase