티스토리 뷰

728x90



이번 포스팅에서는 SQLite 로 만들어진 기존 sample project 를 ROOM 으로 migration 하기위해 ROOM 의 3 구성요소인 Database, Entity, Dao 를 추가할 것이다.

 

참고로, 지난 포스팅에서는 UI, DB 생성, CRUD, column 추가, DB 확인, ROOM 에 대해 알아 보았다.

[Android/Database] - SQLite 에서 ROOM 까지 (2) - UI 구성

[Android/Database] - SQLite 에서 ROOM 까지 (3) - SQLiteOpenHelper

[Android/Database] - SQLite 에서 ROOM 까지 (4) - SQLite 를 이용한 CRUD

[Android/Database] - SQLite 에서 ROOM 까지 (5) - SQLite 로 생성된 기존 DB 에 column 추가하기

[Android/Database] - SQLite 에서 ROOM 까지 (6) - DB 확인하기

[Android/Database] - SQLite 에서 ROOM 까지 (7) - ROOM 이란?



Step 1: Library 추가하기

하단 library 및 annotation processor 를 app gradle file 에 추가한다.

(lifecycle 은 view model 을 위해 추가함.)

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:recyclerview-v7:28.0.0'
// Room
implementation 'android.arch.persistence.room:runtime:1.1.1'
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
// Lifecycle
implementation 'android.arch.lifecycle:extensions:1.1.1'
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
}
view raw build.gradle hosted with ❤ by GitHub



Step 2: Entity class 추가하기

Entity file 은 class 의 변수들이 column 이 되어 database 의 table 이 된다.

◼ Annotation

@Entity(tableName = StudentEntry.TABLE_NAME)

Table 이름을 선언한다. (기본적으로 entity class 이름을 database table 이름으로 인식)

 

@PrimaryKey

각 entity 는 1개의 primary key 를 가져야 한다.

 

@ColumnInfo

Table 내 column 을 변수와 매칭

 

@Entity(tableName = StudentEntry.TABLE_NAME)
public class PhStudentEntity {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = StudentEntry._ID)
private int mId;
@ColumnInfo(name = StudentEntry.GRADE)
private int grade;
@ColumnInfo(name = StudentEntry.NUMBER)
private int number;
@ColumnInfo(name = StudentEntry.NAME)
private String name;
@ColumnInfo(name = StudentEntry.AGE)
private int age;
public int getId() {
return mId;
}
public void setId(int a_id) {
mId = a_id;
}
public int getGrade() {
return grade;
}
public void setGrade(int a_strGrade) {
grade = a_strGrade;
}
public int getNumber() {
return number;
}
public void setNumber(int a_strNumber) {
number = a_strNumber;
}
public String getName() {
return name;
}
public void setName(String a_strName) {
name = a_strName;
}
public int getAge() {
return age;
}
public void setAge(int a_strAge) {
age = a_strAge;
}
}



Step 3: DAO class 추가하기

DAO 는 database 에 접근할 수 있는 메소드를 포함하며 SQL 쿼리를 지정할 수 있다.

◼ Annotation

@insert

Entity set 을 삽입한다.

@Entity로 정의된 class만 인자로 받거나, 그 class의 collection 또는 array 만 인자로 받을 수 있다.

인자가 하나인 경우 long type 의 return (insert 된 row Id)을 받을 수 있고, 여러 개인 경우 long[], List 을 받을 수 있다.

"onConflict = OnConflictStrategy.REPLACE" option 으로 update 와 동일한 기능을 할 수 있다.

 

@update

Entity set 을 갱신한다.

Return 값으로 업데이트된 행 수를 받을 수 있다.

 

@delete

Entity set 을 삭제한다.

Return 값으로 삭제된 행 수를 받을 수 있다.

 

@query

@Query를 사용하여 DB를 조회할 수 있다.

Compile time 에 return 되는 object 의 field 와 sql 결과로 나오는 column 의 이름이 맞는지 확인하여 일부가 match되면 warning, match 되는게 없다면 error를 보낸다.

 

@Dao
public interface PhStudentDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
Long insert(PhStudentEntity a_studentEntity);
@Update
void update(PhStudentEntity a_studentEntity);
@Query("DELETE FROM " + StudentEntry.TABLE_NAME + " WHERE _id = :a_id")
void deleteById(int a_id);
@Query("SELECT * FROM " + StudentEntry.TABLE_NAME)
List<PhStudentEntity> getAllStudents();
}



Step 4: Database class 추가하기

데이터베이스의 holder를 구성하며 지속적인 관계형 데이터의 기본 연결을 위한 access point 역할을 한다.

◼ "@Database" 로 annotation 이 지정된 클래스는 다음 조건을 충족해야 한다.

RoomDatabase 를 extends 하는 abstract class 여야 한다.

Annotation 내에 entities 를 포함해야 한다.

클래스 내부에 인수가 0 개인 @Dao annotation 이 지정된 클래스를 반환하는 abstract class 를 포함한다.

 

@Database(
entities = {PhStudentEntity.class},
version = 2
)
public abstract class PhDatabase extends RoomDatabase {
public abstract PhStudentDao studentDao();
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase a_database) {
// Since we didn't alter the table, there's nothing else to do here.
}
};
private static PhDatabase INSTANCE;
public static PhDatabase getInstance(final Context a_context) {
if (INSTANCE == null) {
synchronized (PhDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(a_context.getApplicationContext(),
PhDatabase.class, PhDatabaseContract.DATABASE_NAME)
.addMigrations(MIGRATION_1_2)
.build();
}
}
}
return INSTANCE;
}
}
view raw PhDatabase.java hosted with ❤ by GitHub



Source code

https://github.com/parkho79/FromSQLiteToRoom_3



728x90
댓글