Room은 SQLite에 대한 추상화 레이어를 제공하여 원할한 데이터베이스 엑세스를 지원하는 동시에SQLite를 완벽히 할용 한다.
build.gradle
dependencies {
def room_version = "2.2.5"
//Room//
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// optional - RxJava support for Room
implementation "androidx.room:room-rxjava2:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// Test helpers
testImplementation "androidx.room:room-testing:$room_version"
kapt "androidx.room:room-compiler:$room_version"
}
@Entity(tableName = "USER")
data class UserEntity(@ColumnInfo(name = "user_id") var userId: String,
@ColumnInfo(name = "user_pw") var userPw: String,
@ColumnInfo(name = "user_name") var userName: String
){
@PrimaryKey(autoGenerate = true) var id: Long = 0
}
@Dao
interface UserDao {
//죄회
@Query("SELECT * FROM user")
fun getUser(): List<UserEntity>
//입력
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(vararg user: UserEntity)
//삭제
@Query("DELETE from user")
fun delete()
}
@Database(version = 1,
entities = [UserEntity::class]
)
abstract class UserDB : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
private var INSTANCE: UserDB? = null
fun getInstance(context: Context): UserDB? {
if (INSTANCE == null) {
synchronized(UserDB::class) {
INSTANCE = Room.databaseBuilder(
context.applicationContext,
UserDB::class.java, "user.db"
)
.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE
}
fun destroyInstance() {
INSTANCE = null
}
}
}
class MainActivity : AppCompatActivity() {
private var userDb: UserDB? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userDb = UserDB.getInstance(this)
//USER DB에 저장
val runnable = Runnable {
val newUser = UserEntity(
"USER0_ID",
"USER_PW",
"USER_NAME"
)
userDb?.userDao()?.insert(newUser)
}
val thread = Thread(runnable)
thread.start()
}
}
안드로이드Room7가지 유용한 팁
https://developer.android.com/training/data-storage/room/defining-data