본문 바로가기

Android/Database

Android Room 일괄 삽입 또는 업데이트 (Kotlin)

interface ItemDao<T> {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(entity: Item) : Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg entity: Item) 

    @Update
    fun update(entity: Item)

    @Update
    fun updateAll(vararg entity: Item)    
}

 

여러 개체 삽입

// insert multiple items
itemDao.insertAll(item1, item2, item3)

목록을 varargs로 변환

// insert list of items
val items = listOf<Item>(item1, item2, item3)
itemDao.insertAll(*items.toTypedArray())

배열을 varargs로 변환

// insert array of items
val items = arrayOf(item1, item2, item3)
itemDao.insertAll(*items)

 

편의를 위한 메서드 정의

DAO 클래스를 사용하여 나타낼 수 있는 여러 편의성 쿼리가 있습니다. 이 문서에는 일반적인 예가 나와 있습니다.

삽입

DAO 메서드를 만들고 @Insert 주석을 달 때 Room은 단일 트랜잭션으로 모든 매개변수를 데이터베이스에 삽입하는 구현을 생성합니다.

다음 코드 스니펫은 몇 가지 쿼리 예를 보여줍니다.

    @Dao
    interface MyDao {
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        fun insertUsers(vararg users: User)

        @Insert
        fun insertBothUsers(user1: User, user2: User)

        @Insert
        fun insertUsersAndFriends(user: User, friends: List<User>)
    }
    

@Insert 메서드는 매개변수를 하나만 수신하면 삽입된 항목의 새 rowId인 long을 반환할 수 있습니다. 매개변수가 배열 또는 컬렉션이면 대신 long[] 또는 List<Long>을 반환해야 합니다.

자세한 내용은 @Insert 주석에 관한 참조 문서와 rowid 테이블에 관한 SQLite 문서를 참조하세요.

업데이트

Update 편의 메서드는 매개변수로 제공된 항목 세트를 데이터베이스에서 수정합니다. 이 메서드는 각 항목의 기본 키와 일치하는 쿼리를 사용합니다.

다음 코드 스니펫은 이 메서드를 정의하는 방법을 보여줍니다.

    @Dao
    interface MyDao {
        @Update
        fun updateUsers(vararg users: User)
    }
    

 

반응형

'Android > Database' 카테고리의 다른 글

문자열 자르기 (kotlin)  (0) 2021.03.25
Room 쿼리문 샘플 (kotlin)  (0) 2021.03.23