我正试图在Room Persistence Library中实现多对多关系。我正在尝试创建Notes App with Tags
。
这个想法是:
笔记会有多个标签。
标签会有多个音符。
在RecyclerView中显示所有注释以及标记。
为实现这一目标,我创建了两个模型 Note.java , Tag.java 和 TagJoin 模型来存储关系b / w笔记和标签。使用@Relation
注释很容易实现一对一。
以下是我的模特
@Entity(tableName = "notes")
public class Note {
@PrimaryKey
@NonNull
public final String id;
@ColumnInfo(name = "note")
public String note;
@Ignore
public List<Tag> tags;
@Ignore
public Note(String note) {
this(UUID.randomUUID().toString(), note);
}
public Note(String id, String note) {
this.id = id;
this.note = note;
}
public String getId() {
return id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
@Entity(tableName = "note_tag_join",
primaryKeys = {"noteId", "tagId"},
foreignKeys = {
@ForeignKey(
entity = Note.class,
parentColumns = "id",
childColumns = "noteId",
onDelete = CASCADE),
@ForeignKey(
entity = Tag.class,
parentColumns = "id",
childColumns = "tagId",
onDelete = CASCADE)},
indices = {
@Index(value = "noteId"),
@Index(value = "tagId")
}
)
public static class TagJoin {
@NonNull
public final String noteId;
@NonNull
public final String tagId;
public TagJoin(String noteId, String tagId) {
this.noteId = noteId;
this.tagId = tagId;
}
}
}
标签型号:
@Entity(tableName = "tags", indices = {@Index(value = "name", unique = true)})
public class Tag {
@PrimaryKey
@NonNull
public String id;
@ColumnInfo(name = "name")
public String name;
@Ignore
public Tag(String name) {
this(UUID.randomUUID().toString(), name);
}
public Tag(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Notes Dao:
@Dao
public interface NoteDao {
@Query("SELECT * FROM notes ORDER BY id DESC")
LiveData<List<Note>> getAllNotes();
@Insert
long insert(Note note);
@Update
void update(Note note);
@Delete
void delete(Note note);
@Query("DELETE FROM notes")
void deleteAll();
@Query("SELECT COUNT(*) FROM notes")
int getNotesCount();
@Query("SELECT notes.* FROM notes\n" +
"INNER JOIN note_tag_join ON notes.id=note_tag_join.noteId\n" +
"WHERE note_tag_join.tagId=:tagId")
List<Note> getAllNotesOfTag(String tagId);
@Insert
void insert(Note.TagJoin... joins);
@Delete
void delete(Note.TagJoin... joins);
}
到目前为止一切都很好。现在我想在RecyclerView中显示Notes,但我找不到一种方法来同时获取所有Notes以及Tags。 一种方法是,在onBindViewHolder方法中获取每个音符的标签,我认为这是错误的,因为我们必须在每次显示行时查询数据库。
请提供建议。
PS:我已经遵循了本文提供的代码 https://commonsware.com/AndroidArch/previews/mn-relations-in-room