使用@Relation批注的会议室-一对多关系where子句子关系

时间:2019-05-31 01:22:07

标签: android android-room android-architecture-components

使用@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开发人员正在阅读本文,谢谢,我讨厌。

还有另一种方法吗?

2 个答案:

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