Room 是Google簡化Sqlite專門提供的封裝架構。
擁有Sqlite的所有功能
使用簡單,通過注解的方法實作相關功能,類似于GreenDao,編譯時自動生成實作類。
支援LiveData LifeCycle Paging
1.依賴
implementation 'android.arch.persistence.room:runtime:1.1.1'
implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
2.資料庫的建立
建立一個抽象類繼承RoomDatabase對象,靜态代碼塊,初始化資料庫對象,三個參數,1-上下文,2-目前對象,3-資料庫名稱。下面還有針對資料庫的配置。
@Database(entities = {Cache.class}, version = 1,exportSchema =true)
public abstract class CacheDatabase extends RoomDatabase {
private static final CacheDatabase database;
static {
//建立一個記憶體資料庫
//但是這種資料庫的資料隻存在于記憶體中,也就是程序被殺之後,資料随之丢失
//Room.inMemoryDatabaseBuilder()
database = Room.databaseBuilder(AppGlobals.getApplication(), CacheDatabase.class, "cache")
//是否允許在主線程進行查詢
//.allowMainThreadQueries()
//資料庫建立和打開後的回調
//.addCallback()
//設定查詢的線程池
//.setQueryExecutor()
//room的日志模式
//.setJournalMode()
//資料庫更新異常之後的復原
//.fallbackToDestructiveMigration()
//資料庫更新異常後根據指定版本進行復原
//.fallbackToDestructiveMigrationFrom()
//資料庫遷移 監聽 ,可以進行修改
// .addMigrations(CacheDatabase.sMigration)
.build();
}
public static CacheDatabase get() {
return database;
}
// 擷取操作對象
public abstract CacheDao getCacheDao();
}
其中,exportSchema =true是日志模式,要實作配置
build.gradle–>android–>defaultConfig裡
javaCompileOptions{
annotationProcessorOptions{
arguments=["room.schemaLocation":"$projectDir/schemas".toString()]
}
}
.addMigrations
遷移涉及到資料庫更新的字段改變。
// 添加功能
.addMigrations( sMigration)
// 具體實作
static Migration sMigration = new Migration(1, 3) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("alter table teacher rename to student");
}
};
3.實體
@Entity
public class Cache implements Serializable {
@PrimaryKey
String key;
byte[] data;
}
4.Dao對象
@Dao
public interface CacheDao {
@Insert(onConflict = OnConflictStrategy.ABORT)
void insert(Cache cache);
@Query(("select * from cache where 'key'= :key"))
Cache getCache(String key);
@Delete
long delete(Cache cache);
@Update(onConflict = OnConflictStrategy.ABORT)
void update();
}
5.注解
@Database 資料庫的主對象
@Database(entities = {Cache.class}, version = 1,exportSchema =true) entities 是個數組,涉及哪些表,版本号、導出更新的資料庫日志。
@columnInfo(name="info") 更改列的名字
@Dao 操作資料庫的對象,如:增删改查
@Embedded 嵌套對象
@Entity 表的對象
@PrimartKey 主鍵
@Delete 删除
@Ingore 忽略在資料庫産生列
@Index 加快查詢操作,副作用減慢插入或者更新
@Foreignkey 外鍵關聯
@Tranation
@TypeConverter
Dao
注解—涉及具體查詢方法,是個接口,編譯的時候自動生成實作類。
@Dao
public interface CacheDao {
@Insert(onConflict = OnConflictStrategy.ABORT)
void insert(Cache cache);
@Query(("select * from cache where 'key'= :key"))
Cache getCache(String key);
@Delete
long delete(Cache cache);
@Update(onConflict = OnConflictStrategy.ABORT)
void update();
}
沖突政策
增加和修改的時候,有可能已經存在的資料,OnConflictStrategy 就是解決這種情況的沖突政策。
int REPLACE = 1;
/**
* OnConflict strategy constant to rollback the transaction.
* 復原
*/
int ROLLBACK = 2;
/**
* OnConflict strategy constant to abort the transaction.
* 放棄
*/
int ABORT = 3;
/**
* OnConflict strategy constant to fail the transaction.
*/
int FAIL = 4;
/**
* OnConflict strategy constant to ignore the conflict.
*/
int IGNORE = 5;
foreignKeys
主要是為了和其他對象有關聯的時候使用。下面這句就是目前對象和User對象進行對象,都是通過各自的id進行關聯。onDelete 和onUpdate 使用的外鍵政策。這個政策主要針對目前的表資料的變化引起關聯表的變化的政策機制。
@Entity(tableName = "cache",
foreignKeys = {@ForeignKey(entity = User.class,parentColumns = "id",childColumns = "id", onDelete = ForeignKey.RESTRICT,onUpdate = ForeignKey.RESTRICT)})
ForeignKey:
int NO_ACTION = 1; 不處理
int RESTRICT = 2; 若主表删除,相關的關聯表立即也删除。
int SET_NULL = 3; 設定null
int SET_DEFAULT = 4; 設定預設值
int CASCADE = 5; 類似RESTRICT,與之相關的每個關聯表都響應。
6.具體使用
CacheDatabase.getCacheDatabase().getCacheDao().insert(cache);
CacheDatabase.getCacheDatabase().getCacheDao().delete(cache);