KotlinでRoomを利用するシンプルな例


[Android とアーキテクチャ](https://developers-jp.googleblog.com/2017/06/android-and-architecture.html)
![](https://2.bp.blogspot.com/-JOfLef-C7b4/WRzl-wLKqLI/AAAAAAAAEM4/9aHbKY7OHM4j1cTfAQcLHLi4nS5ngOU3QCLcB/s1600/Screen%2BShot%2B2017-05-17%2Bat%2B5.08.05%2BPM.png)

とりあえず1行だけ書き込むというだけのサンプルです

```kotlin:MyDao.kt
@Dao
interface MyDao {
    @get:Query("SELECT * FROM MyEntity")
    val all: List<MyEntity>

    @Query("SELECT * FROM MyEntity WHERE node_id IN (:nodeIds)")
    fun loadAllByIds(nodeIds: IntArray): List<MyEntity>

    @Query("SELECT * FROM MyEntity WHERE node_id LIKE :nodeId AND device_class LIKE :deviceClass LIMIT 1")
    fun findByName(nodeId: String, deviceClass: String): MyEntity

    @Insert
    fun insertAll(vararg users: MyEntity)

    @Delete
    fun delete(node: MyEntity)

}
```

```kotlin:MyEntity.kt
@Entity
class MyEntity {
    @PrimaryKey(autoGenerate = true)
    var  myEntityId: Int = 0

    @ColumnInfo(name = "node_id")
    var nodeId: String? = null

    @ColumnInfo(name = "device_class")
    var deviceClass: String? = null

    companion object {
        fun create(_nodeId:String, _deviceClass:String) : MyEntity{
            val node = MyEntity()
            node.nodeId = _nodeId
            node.deviceClass = _deviceClass
            return node
        }
    }
}


```

```kotlin:MyDataBase.kt

@Database(entities = arrayOf(MyEntity::class) , version = 1)
abstract class MyDatabase: RoomDatabase() {
    abstract fun userDao(): MyDao

    companion object {
        private var INSTANCE: MyDatabase? = null

        fun getInstance(context: Context): MyDatabase? {
            if (INSTANCE == null) {
                synchronized(MyDatabase::class) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            MyDatabase::class.java, "MyDatabase.db")
                            .build()
                }
            }
            return INSTANCE
        }

        fun destroyInstance() {
            INSTANCE = null
        }
    }
}

```


```kotlin:MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
                        .build());

        val myEntity = MyEntity.create("myNode","myDeviceClass")
        val context = applicationContext ?: return
        val db = MyDatabase.getInstance(context)!!
        Completable.fromAction { val id = db.userDao().insertAll(myEntity)}
                .subscribeOn(Schedulers.io())
                .subscribe()


    }
}

```

```gradle:build.gradle
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "yy.org.roomsample"
        minSdkVersion 27
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    // Sthetho Sqliteデバッグツールとして
    debugImplementation'com.facebook.stetho:stetho:1.5.0'
    debugImplementation'com.facebook.stetho:stetho-okhttp3:1.5.0'

    // ROOM
    def room_version = "1.1.1"
    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version"
    kapt "android.arch.persistence.room:compiler:$room_version"
    // optional - RxJava support for Room
    implementation "android.arch.persistence.room:rxjava2:$room_version"
    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "android.arch.persistence.room:guava:$room_version"
    // Test helpers
    testImplementation "android.arch.persistence.room:testing:$room_version"


}

```

Stethoを入れたので、
Chromeから[chrome://inspect](chrome://inspect)でDBに書き込まれていることを確認できます

<img width="925" alt="スクリーンショット 2018-06-25 1.09.42.png" src="https://qiita-image-store.s3.amazonaws.com/0/6968/006b907f-19ae-c1b7-463f-82be6bac6ea7.png">



# 用語

[POJO](https://ja.wikipedia.org/wiki/Plain_Old_Java_Object)
Plain Old Java Object (POJO) は、あるJavaオブジェクトがごく普通のJavaオブジェクトであることを強調した名称。
特定のフレームワークや依存関係の強いライブラリを使わずに実現できるクラスのことで、ごく単純な構成のJavaクラスであることを強調した名称。
EntityやDatabase,DaoはPOJOである。