개발일지

Android in A..Z - Room (관계) 본문

Android (안드로이드)/Room

Android in A..Z - Room (관계)

강태종 2021. 1. 17. 03:15

관계

데이터베이스에서 각 테이블마다 관계가 존재하는 것처럼 Room에도 관계를 설정할 수 있다.


Drawer와 ToDo 의 1 : N관계

 

Drawer

관계에서 사용할 Column을 인덱싱한다. (PrimaryKey를 관계에서 사용할 경우 인덱싱을 할 필요가 없다.)

@Entity(
        indices = [
            Index(value = ["name"], unique = true)
        ]
)
data class Drawer(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    var name: String = "",
)
  • indices : Index를 나열한다
  • Index
    • value : 인덱싱할 column
    • unique : 고유값을 가지는지 설정

ToDo

@Entity에서 forignKeys를 사용하여 FK를 설정한다.

@Entity(
        foreignKeys = [
            ForeignKey(
                    entity = Drawer::class, 
                    parentColumns = ["name"],
                    childColumns = ["drawerName"],
                    onDelete = ForeignKey.CASCADE,
                    onUpdate = ForeignKey.CASCADE
            )
        ]
)
data class ToDo(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    var text: String = "",
    var drawerName: String = "",
    var isFinished: Boolean = false
)
  • foreignKeys : FK를 나열한다.
  • ForeignKey
    • entity : 관계를 만들 Entity
    • parentColumns : FK로 가져오는 Column의 이름
    • childColumns : FK로 받을 Column의 이름
    • onDelete : Delete를 실행할 때 제약사항
    • onUpdate : Update를 실행할 때 제약사항

DrawerWithToDo

새로운 class를 만들어서 관계를 설정한 후에 DAO를 통해 데이터를 받을 수 있다. (@Entity 선언할 필요 없다.)

data class DrawerWithToDo(
        @Embedded
        var drawer: Drawer = Drawer(),

        @Relation(
                parentColumn = "name",
                entityColumn = "drawerName"
        )
        val todoList: MutableList<ToDo> = mutableListOf()
)
  • @Embedded : Entity안에 class형식의 변수가 있을 경우 해당 class 변수를 모두 column으로 저장한다.
  • @Relation : 관계를 설정한다.
    • parentColumn : 참조하는 FK의 Column
    • entityColumn : 참조받는 FK의 Column

DrawerDao

DrawerDao에서 DrawerWithToDo Entity를 얻어서 사용한다.

@Dao
interface DrawerDao : BaseDao<Drawer> {
    @Query("SELECT * FROM Drawer")
    fun findLiveData(): LiveData<MutableList<Drawer>>

    @Query("SELECT * FROM Drawer")
    fun findLiveDataWithToDo(): LiveData<MutableList<DrawerWithToDo>>
}

그 외에 관계

developer.android.com/training/data-storage/room/relationships?hl=ko

 

객체 간 관계 정의  |  Android 개발자  |  Android Developers

SQLite는 관계형 데이터베이스이므로 항목 간 관계를 지정할 수 있습니다. 대부분의 객체 관계 매핑(ORM) 라이브러리에서는 항목 객체가 서로를 참조할 수 있지만, Room은 이러한 상호 참조를 명시

developer.android.com


Git (예제코드)

github.com/KangTaeJong98/Example/tree/main/Android/Room

 

KangTaeJong98/Example

My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.

github.com

 

Comments