2
두 모델 (테이블) WordGroups
및 Words
이 있으며 그 사이의 관계는 1 대 다수입니다. 그래서 내 모델과 같은 Dao
보기 :Android 룸 : LiveData와의 관계
@Entity
public class WordGroup {
@PrimaryKey
private int id;
@Ignore
private List<Word> words;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Word> getWords() {
return words;
}
public void setWords(List<Word> words) {
this.words = words;
}
}
@Entity
public class Word {
@PrimaryKey
private int id;
@ForeignKey(entity = WordGroup.class, parentColumns = "id", childColumns = "wordGroupId")
private int wordGroupId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getWordGroupId() {
return wordGroupId;
}
public void setWordGroupId(int wordGroupId) {
this.wordGroupId = wordGroupId;
}
}
지금
@Dao
public interface Dao {
@Query("select * from WordGroup where id = :id")
LiveData<WordGroup> selectWordGroupById(int id);
@Query("select * from WordGroup")
LiveData<List<WordGroup>> selectAllWordGroups();
@Query("select * from Word where wordGroupId = :wordGroupId")
LiveData<List<Word>> selectWordsByWordGroupId(int wordGroupId);
}
나는 또한
WordGroup
를 선택하고 메소드가 설정 한 그
Word
의
Transformations
사용 : 지금
public LiveData<WordGroup> getWordGroupWithWords(int id) {
LiveData<WordGroup> wordGroupLiveData = dao.selectWordGroupById(id);
LiveData<WordGroup> wordGroupWithWordsLiveData = Transformations.switchMap(wordGroupLiveData, inputWordGroup -> {
LiveData<List<Word>> wordsLiveData = dao.selectWordsByWordGroupId(inputWordGroup.getId());
LiveData<WordGroup> outputWordGroupsLiveData = Transformations.map(wordsLiveData, inputWords -> {
inputWordGroup.setWords(inputWords);
return inputWordGroup;
});
return outputWordGroupsLiveData;
});
return wordGroupWithWordsLiveData;
}
모든 WordGroup
을 선택하는 방법을 쓰고 싶습니다. 또한를 설정합니다. 각 WordGroup
에 대해s입니다.
public LiveData<List<WordGroup>> getAllWordGroupsWithWords();
이 기사를 확인하십시오. https://medium.com/@rezabigdeli6/android-room-handling-relations-using-livedata-2d892e40bd53 –