我有一个父实体集合:
@Entity(tableName = "collections")
public class Collection implements Serializable {
@PrimaryKey
@NonNull
public String id;
public String collTitle;
public int isFavorite;
public int wordCount;
Collection(String collTitle, int isFavorite, int wordCount) {
this(UUID.randomUUID().toString(), collTitle, isFavorite, wordCount);
}
@Ignore
Collection(@NonNull String id, String collTitle, int isFavorite, int wordCount) {
this.id = id;
this.collTitle = collTitle;
this.isFavorite = isFavorite;
this.wordCount = wordCount;
}
}
和一个子实体字词:
@Entity(tableName = "words",
foreignKeys = @ForeignKey(
entity = Collection.class,
parentColumns = "id",
childColumns = "collId",
onDelete = SET_DEFAULT),
indices = @Index("collId"))
public class Word implements Serializable {
@PrimaryKey
@NonNull
public final String id;
public String wordTitle;
public String collId;
public String pageNum;
public int isFavorite;
public String wordNotes;
@Ignore
Word(String wordTitle, String collId, String pageNum, int isFavorite, String wordNotes) {
this(UUID.randomUUID().toString(), wordTitle, collId, pageNum, isFavorite, wordNotes);
}
Word(@NonNull String id, String wordTitle, String collId, String pageNum, int isFavorite,
String wordNotes) {
this.id = id;
this.wordTitle = wordTitle;
this.collId = collId;
this.pageNum = pageNum;
this.isFavorite = isFavorite;
this.wordNotes = wordNotes;
}
}
在插入新集合时,我将wordCount设置为0,因为每个新集合都将有0个与之关联的单词。但是,在插入新Word时,我必须从定义的集合中选择一个集合,并将其“ id”用作“ collId”(外键)。
现在,我需要使用“ wordCount”字段检索包含Collection对象的列表,该字段包含与每个Collection对象关联的实际单词数。如前所述,在插入Collection对象时,'wordCount'字段的值为0。
我只是希望我能明确地说出我的问题。请提出一个符合我目的的查询。而且我不想以新的POJO类的形式获得结果,例如CollectionsAndWords。
任何帮助都将是一个很大的帮助!
答案 0 :(得分:1)
好的,我通过以下方式解决了该问题:
在我的Collection实体中,我对wordCount进行了如下注释:
@ColumnInfo(name = "word_count")
public int wordCount;
并通过删除以下字段来更改构造函数:
Collection(String collTitle, int isFavorite) {
this(UUID.randomUUID().toString(), collTitle, isFavorite);
}
@Ignore
Collection(@NonNull String id, String collTitle, int isFavorite) {
this.id = id;
this.collTitle = collTitle;
this.isFavorite = isFavorite;
}
最后,我在DAO中添加了以下查询方法:
@Query("SELECT collections.id, collections.collTitle, collections.isFavorite, " +
"COUNT(words.collId) as word_count " +
"FROM collections " +
"LEFT JOIN words " +
"ON collections.id = words.collId " +
"GROUP BY collections.id " +
"ORDER BY collections.collTitle")
List<Collection> findAllCollsWithCount();
正确使用LEFT JOIN可以帮到我所有的麻烦。
请注意,在上面的查询中,我不是在检索wordCount字段,而是在计算一个新字段并将其映射到wordCount。如果我从集合表中检索wordCount以及其他列,则会得到02列,它们的名称分别为word_count;一个具有0值,另一个具有计算值(COUNT())。我还尝试使用@Ignore注释wordCount,但随后Room无法找到任何将word_count映射到的列。
但是,就目前而言,上述解决方案完全可以满足我的目的,因此就是答案。可能会帮助遇到相同问题的人。
谢谢!