Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- MINUS
- vuex
- Service
- map
- Generic
- animation
- Swift
- 생명주기
- mongoose
- ConstraintLayout
- union
- docker
- elementAt
- recyclerview
- Filter
- Kotlin
- Interface
- LiveData
- AWS
- lifecycle
- Foreign Key
- CLASS
- list
- collection
- react native
- enum
- class component
- function
- ReactNative
- docker-compose
Archives
- Today
- Total
개발 일기
Android Realm 사용방법 본문
Realm이란?
Realm 플랫폼의 핵심인 Realm 데이터베이스는 오픈 소스로 모바일 사용에 최적화된 내장 데이터베이스 라이브러리입니다. SQLite나 Core Data 같은 데이터 저장소를 사용하는 경우 Realm 데이터베이스를 경량 관계형 데이터베이스로 뒷받침되는 객체 관계 매핑, 즉 ORM이라고 생각할 수 있습니다. 하지만 Realm은 ORM이 아닙니다. 대신 Realm은 “데이터 컨테이너” 모델을 사용합니다. 데이터 객체는 Realm에 객체로서 저장됩니다. 이 덕분에 Realm은 몇 가지 중요한 장점을 갖습니다.
- Realm은 네이티브 객체 를 저장합니다
- Realm은 zero-copy 입니다
- Realm은 라이브 오브젝트 패턴 을 구현합니다
- Realm은 크로스 플랫폼 입니다
- Realm은 오프라인-우선 입니다
사용방법 :)
- Gradle
dependencies {
classpath "io.realm:realm-gradle-plugin:3.5.0"
}
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'
- App
// Realm 초기화를 진행합니다
Realm.init(this)
// Realm 을 어떻게 생성할 건지 RealmConfiguration을 통해 설정을 합니다.
val config = RealmConfiguration.Builder().name("TestApp")
.schemaVersion(1) // schema 버전 설정
.migration(new Migration()) // Migration 설정 (스키마 변경시 적용)
.build()
Realm.setDefaultConfiguration(config)
- 호출 및 취소
val realm : Realm = Realm.getDefaultInstance()
realm.close
- 모델 생성 방법
open class SignModel : RealmObject() {
@PrimaryKey var unique_key : Long = 0
var points : RealmList<PointModel> = RealmList()
}
모델은 RealmObject 상속을 받아 생성하면 됩니다.
@Required | Null 값을 허용하지 않습니다. |
@Ignore | 해당 내용이 디스크에 저장되지 않습니다. |
@Index | 검색 색인을 추가합니다. |
@Primarykey | 기본키로 설정합니다. |
- Create
// transaction 생성합니다.
// 또다른방법
// realm?.beginTransaction()
// realm?.commitTransaction()
realm?.executeTransaction {
// createObject을 통해 만드는 방법이 있습니다.
// 아니면 copyFromRealm을 통해 기존에 생성되어있던 객체를 가지고도 만들수 있습니다.
val parentModel = it.createObject(SignModel::class.java , tempKey)
for (i in drawView.points) {
val childModel = it.createObject(PointModel::class.java)
parentModel.points.add(childModel)
}
}
- Delete
realm?.executeTransaction {
//unique_key , key와 동일한 값을 가져와서 삭제를 진행을 합니다.
val model = realm?.where(SignModel::class.java)?.equalTo("unique_key" , key)?.findAll()
model?.deleteAllFromRealm()
}
-Update
val model = TestModel()
realm?.executeTransaction {
// 기본키가 존재한다면 기존 객체를 업데이트
// 기본키가 존재하지 않다면 새로운 객체를 만듭니다.
it.copyToRealmOrUpdate(model)
}
-Sort
// unique_key 방식으로 정렬해서 가져옵니다.
val data = realm?.where(SignModel::class.java)?.findAllSorted("unique_key")
'Client > 안드로이드' 카테고리의 다른 글
RecyclerView 이란? (0) | 2020.03.09 |
---|---|
android key Hash 구하기 (0) | 2020.03.07 |
ConstraintLayout (0) | 2020.03.05 |
임시 UI 상태 저장 및 복원 (0) | 2020.03.04 |
Koin(DI) (0) | 2020.03.03 |
Comments