5.Task 3: Create the DAO
https://codelabs.developers.google.com/codelabs/android-training-livedata-viewmodel/#4
다음은 DAO를 만들어 보겠습니다. DAO는 annotate 클래스로 SQL 쿼리를 지정하고 메서드 호출과 연결하는 클래스입니다.
1.DAO 는 interface 혹은 abstract 클래스 여야 합니다.
2.Room 은 clean API를 위해 DAO를 사용합니다.
3.모든 쿼리는 메인 쓰레드가 아닌 다른 쓰레드에서만 사용되어야 합니다.inserting 이나 deleting 같은 작업의 경우 룸 에서 쓰레드 관리를 처리합니다.
이번 예제에서 DAO 는 모든 word를 가져오거나, word를 삽입하거나, 지우는 작업만을 수행할 겁니다.
순서는 1. interface 를 만들고 WordDao선언을 해줍니다. 2.@DAO를 annotation 처리를 해서 Room이 DAO 클래스라는 걸 알게해줍시다. 3. 하나의 word를 삽입하는 method를 만들어 줍시다. 4.insert method에 @Insert 어노테이션을 추가해 줍시다. 5.모든 words를 delete 하는 deleteAll method를 만들어 줍시다. 6.deleteAll Method 에 마찬가지로 어노테이션을 추가해 줍시다. 이 어노테이션은 쿼리로 @Query("DELETE FROM word_table") 입니다. 7. getAllWords() List를 return 하는 메소드를 추가해줍시다. 8. 이 메소드도 쿼리 Annotation을 추가해줍시다. @Query("SELECT * from word_table ORDER BY word ASC")
WordDao Class 의 전체 코드는 이렇습니다.
@Dao
public interface WordDao {
@Insert
void insert(Word word);
@Query("DELETE FROM word_table")
void deleteAll();
@Query("SELECT * from word_table ORDER BY word ASC")
List<Word> getAllWords();
}
'안드로이드 > 공부' 카테고리의 다른 글
블루투스(BLE) 통신 앱 만들기 -1 (0) | 2020.11.08 |
---|---|
안드로이드 Room,LiveData,ViewModel 예제(Codelaps)-6 (0) | 2020.05.05 |
안드로이드 Room,LiveData,ViewModel 예제(Codelaps)-3 (0) | 2020.05.01 |
안드로이드 Room,LiveData,ViewModel 예제(Codelaps)-2 (0) | 2020.05.01 |
안드로이드 Room,LiveData,ViewModel 예제(Codelaps)-1 (0) | 2020.04.30 |