Roomに関する優れた記事がインターネット上に多すぎます。この記事では、私自身の観点からルームの使用法を紹介するだけです。それで十分だと思います。
Room Google Docs:https://developer.android.google.cn/topic/libraries/architecture/room
1.環境構成:
// room 配置
implementation "android.arch.persistence.room:runtime:1.1.1"
implementation "android.arch.persistence.room:rxjava2:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
androidxの場合は、公式Webサイトの構成を参照してください。
2.部屋の構造の概要:
Roomコンポーネントの3つのコア部分は次のとおりです。
1.エンティティデータエンティティクラス。データベース内のテーブル構造に同時にマップされます。
2. Daoデータベーステーブルの操作クラスを追加、削除、変更、およびチェックします。
3.データベースSqLiteデータベースオブジェクトの取得および管理クラス。
3.エンティティアノテーションの概要:
エンティティは注釈です。エンティティでマークされたクラスは、データベース内のテーブルにマップされます。例として、トピックイベントのリマインダー要件を取り上げます。
@Entity(tableName = "topic_match_table",
primaryKeys = {"topic_id", "match_id"},
indices = {
@Index(value = {"topic_id"}),
@Index(value = {"topic_id", "match_id"})
})
@Keep
public class MatchEntity implements Parcelable {
public MatchEntity() {
}
@Ignore
public MatchEntity(int matchId) {
this.mMatchId = matchId;
}
@Ignore
public MatchEntity(String topicId, int matchId, String teamA, String teamB, long timeStart) {
this.mTopicId = topicId;
this.mMatchId = matchId;
this.mTeamA = teamA;
this.mTeamB = teamB;
this.mTimeStart = timeStart;
}
// 话题 id
@ColumnInfo(name = "topic_id")
@NonNull
public String mTopicId;
// 赛事 id
@ColumnInfo(name = "match_id")
@NonNull
public int mMatchId;
// 赛队 A
@ColumnInfo(name = "team_a")
public String mTeamA;
// 赛队 B
@ColumnInfo(name = "team_b")
public String mTeamB;
// 闹钟开始时间
@ColumnInfo(name = "time_start")
public long mTimeStart;
@Ignore
public PendingIntent mPendingIntent;
// 参考 AlarmManager.RTC_WAKEUP
// ELAPSED 开头的代表系统运行逝去的时间,RTC 开头的是世界时钟
// 以WAKEUP结尾的类型能够唤醒设备
// public static final int RTC_WAKEUP = 0;
// public static final int RTC = 1;
// public static final int ELAPSED_REALTIME_WAKEUP = 2;
// public static final int ELAPSED_REALTIME = 3;
// 闹钟类型
@Ignore
public int mAlarmManagerType = AlarmManager.RTC_WAKEUP;
@Override
public String toString() {
String name = MatchEntity.class.getCanonicalName();
if (name == null) {
return super.toString();
}
String timeString = SimpleDateFormat.getDateTimeInstance().format(new Date(mTimeStart));
return name + " -> mTopicId = " +
mTopicId +
" mMatchId = " +
mMatchId +
" mTeamA = " +
mTeamA +
" mTeamB = " +
mTeamB +
" mTimeStart = " +
timeString;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mTopicId);
dest.writeInt(this.mMatchId);
dest.writeString(this.mTeamA);
dest.writeString(this.mTeamB);
dest.writeLong(this.mTimeStart);
dest.writeParcelable(this.mPendingIntent, flags);
dest.writeInt(this.mAlarmManagerType);
}
protected MatchEntity(Parcel in) {
this.mTopicId = in.readString();
this.mMatchId = in.readInt();
this.mTeamA = in.readString();
this.mTeamB = in.readString();
this.mTimeStart = in.readLong();
this.mPendingIntent = in.readParcelable(PendingIntent.class.getClassLoader());
this.mAlarmManagerType = in.readInt();
}
public static final Parcelable.Creator<MatchEntity> CREATOR = new Parcelable.Creator<MatchEntity>() {
@Override
public MatchEntity createFromParcel(Parcel source) {
return new MatchEntity(source);
}
@Override
public MatchEntity[] newArray(int size) {
return new MatchEntity[size];
}
};
}
1. @ Entityアノテーションはクラス宣言で使用されます。tableName属性は、MatchEntityクラスによってデータにマップされたテーブルの名前がtopic_match_tableであることを示します。primaryKeys属性は、共同主キーが作成されることを示します。インデックス属性の値は、2つのインデックスが作成されたことを示します。
2. @Ignoreアノテーションは、プロパティとコンストラクターで使用されます。パラメータなしのコンストラクタを除いて、他のすべてのコンストラクタはこのアノテーションを追加する必要があります。データベーステーブルフィールドにマップされたくない属性は、このアノテーションを追加する必要があります。
3. @ColumnInfoアノテーションは、この属性がデータベーステーブルのフィールド名にマップされていることを示すために属性で使用されます。このアノテーションが追加されていない場合、クラス属性名とテーブルフィールド名は同じです。
4.主キーの属性を設定するには、@ NonNullアノテーションを追加する必要があります。
5. @PrimaryKeyアノテーションを直接使用して、属性の主キーを宣言することもできます。
上記はエンティティコンテンツの一部にすぎず、基本的には十分に習得できます。
4. Daoアノテーションの概要:
Daoアノテーションでマークされたインターフェースは、エンティティの追加、削除、変更、およびチェックの使命を担っています。
@Dao
public interface MatchDao {
@Query("SELECT match_id FROM topic_match_table WHERE topic_id = :topicId")
int[] getTopicMatchesId(String topicId);
@Query("SELECT * FROM topic_match_table")
List<MatchEntity> getAllMatches();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertMatch(MatchEntity... matchEntities);
@Delete
void deleteMatch(MatchEntity... matchEntities);
@Query("DELETE FROM topic_match_table WHERE topic_id = :topicId AND match_id = :matchId")
void deleteMatchById(String topicId, int matchId);
}
1.インターフェースに@Daoのマークが付いているので、抽象クラスにできるかどうか忘れてしまいました。
2.データベースの追加、削除、変更、およびチェックの4つの操作は、それぞれ@Insert / @Delete / @Update / @ Queryの4つのアノテーションに対応します。
3.柔軟な使用。類推削除操作でも@queryアノテーションを使用できます:@Query( "DELETE FROM topic_match_table WHERE topic_id =:topicId AND match_id =:matchId")
4. @InsertアノテーションのonConflictパラメーターの意味は次のとおりです。追加が競合すると、古いデータが直接置き換えられます。
5.詳細については、Roomコンポーネントアノテーションのステートメントの説明を参照してください。
5.データベース注釈の概要:
データベース注釈、いくつかのデータベースの構成に関する情報に注釈を付けます。
@Database(entities = {MatchEntity.class}, version = MatchDatabase.DB_VERSION, exportSchema = false)
public abstract class MatchDatabase extends RoomDatabase {
// you need update this version value when you update database structure
public static final int DB_VERSION = 1;
public static final String DB_NAME = "topic_match.db";
public abstract MatchDao getMatchDao();
}
1.カスタム抽象クラスMatchDatabaseはRoomDatabaseクラスを継承することに注意してください。
2. @Databaseアノテーションは、MatchDatabase抽象クラスでマークされ、データベースの名前、データベース内のテーブル、テーブル構造の履歴データとjsonデータをエクスポートするかどうかを示します。
3. MatchDatabaseは、MatchDaoなどの特定のエンティティの操作クラスを返すパブリック抽象メソッドを提供する必要があります。
6.部屋の使用の概要:
public class MatchRoomHelper {
private static MatchDatabase MATCH_DATABASE;
private static MatchRoomHelper INSTANCE;
private MatchRoomHelper(Context applicationContext) {
MATCH_DATABASE = Room.databaseBuilder(applicationContext, MatchDatabase.class, MatchDatabase.DB_NAME)
.allowMainThreadQueries() // 允许在主线程执行数据库操作
.build();
}
public synchronized static MatchRoomHelper getInstance(Context applicationContext) {
if (INSTANCE == null) {
INSTANCE = new MatchRoomHelper(applicationContext);
}
return INSTANCE;
}
public List<MatchEntity> getAllMatches() {
return MATCH_DATABASE.getMatchDao().getAllMatches();
}
public int[] getTopicMatchesId(String topicId) {
return MATCH_DATABASE.getMatchDao().getTopicMatchesId(topicId);
}
public synchronized void insertMatch(MatchEntity... matchEntities) {
MATCH_DATABASE.getMatchDao().insertMatch(matchEntities);
}
public synchronized void deleteMatch(MatchEntity... matchEntities) {
MATCH_DATABASE.getMatchDao().deleteMatch(matchEntities);
}
}
1. MatchDatabaseは、実際のデータベース構成ベアリングクラスです。Room.databaseBuilder()を使用してデータベースオブジェクトを作成できます。MatchRoomHelperコンストラクターコードを参照してください。
2.データベース操作をメインスレッドで実行できるかどうかを示すallowMainThreadQueries()構成に注意してください。デフォルトでは許可されていません。許可されていない場合、UIスレッドでのデータベース操作がクラッシュします。
3. MatchDatabaseデータベースオブジェクトを繰り返し作成すること、またはシングルトンモードを使用することはお勧めしませんか?!
4. MatchRoomHelperを介してシングルトンMatchDatabaseデータベースオブジェクトを取得し、次にMatchDaoオブジェクトを取得します。対応するエンティティを追加、削除、変更、および確認できます。