The field's same name issue in the tables, when join tables in ROOM

我的梦境 提交于 2019-12-01 14:48:23
  1. You don't need a separate dao.

  2. Except for one plain, "@Embedded" annotation, the other annotations have to set a prefix: @Embedded(prefix = "favorite_") and @Embedded(prefix = "bookmark_")

  3. In your query, your selected fields have to have the prefix.

Instead of

select * from word join bookmark join favorite // pseudo code

You have to alias the fields to your prefix:

select word.*, bookmark.id as bookmark_id..., favorite.id as favorite_id... from...

This prevents the three id columns to override each other in the query. And with the prefix, the dao will expect all columns of that table to have that prefix in front of the actual column name.

Also what exact error do you get?

I'd guess there might be a NPE. That might have to do with your query. So if you can include the query as well, it would help find the issue.

To solve the "Count" or "Sum" field problem, I used the new compound data class. As below:

public static class CategoryAndEssentials {
    @Embedded
    private BookmarkCategory bookmarkCategory;

    private int wordCount;

    public BookmarkCategory getBookmarkCategory() { return bookmarkCategory; }
    public void setBookmarkCategory(BookmarkCategory bookmarkCategory) { this.bookmarkCategory = bookmarkCategory;}
    public int getWordCount() { return wordCount; }
    public void setWordCount(int wordCount) { this.wordCount = wordCount; }
}

And in the query definition, in Dao class, I referred to this field:

@Query("SELECT " +
            "bookmarkCategory.*, " +
            "COUNT(bookmark.category_id) AS wordCount, " +
        "FROM bookmarkCategory LEFT JOIN bookmark " +
        "ON bookmarkCategory.id = bookmark.category_id " +
        "GROUP BY bookmarkCategory.id ")
LiveData<List<EntityClassForJoinTables.CategoryAndEssentials>> getAllCategoriesAndEssentials();

Note that the alias column in query must have a same as the variable defined in the compound data class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!