新聞中心
如何在Android中與Room組件?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
Room其實(shí)就是一個orm,抽象了SQLite的使用,但是它作為Android的親兒子orm,并且原生支持LiveData和Rxjava嵌套使用,學(xué)習(xí)一下還是不錯的。
Room有3個主要組件
Database :數(shù)據(jù)庫
Entity : 代表數(shù)據(jù)庫一個表結(jié)構(gòu)
Dao : 包含訪問數(shù)據(jù)庫的方法
簡單使用
添加Google Maven倉庫
allprojects { repositories { jcenter() google() } }
添加依賴
dependencies { // Room implementation "android.arch.persistence.room:runtime:1.0.0" annotationProcessor "android.arch.persistence.room:compiler:1.0.0" }
定義數(shù)據(jù)表實(shí)體類
班級表
@Entity(tableName = "tb_class") public class ClassEntity { @PrimaryKey private long id; }
學(xué)生表
//指示數(shù)據(jù)表實(shí)體類 @Entity(tableName = "tb_student",//定義表名 indices = @Index(value = {"name", "sex"}, unique = true),//定義索引 foreignKeys = {@ForeignKey(entity = ClassEntity.class, parentColumns = "id", childColumns = "class_id")})//定義外鍵 public class StudentEntity { @PrimaryKey //定義主鍵 private long id; @ColumnInfo(name = "name")//定義數(shù)據(jù)表中的字段名 private String name; @ColumnInfo(name = "sex") private int sex; @Ignore//指示Room需要忽略的字段或方法 private String ignoreText; @ColumnInfo(name = "class_id") private String class_id; //setter and getter }
Entity注解可選參數(shù)
public @interface Entity { //定義表名 String tableName() default ""; //定義索引 Index[] indices() default {}; //設(shè)為true則父類的索引會自動被當(dāng)前類繼承 boolean inheritSuperIndices() default false; //定義主鍵 String[] primaryKeys() default {}; //定義外鍵 ForeignKey[] foreignKeys() default {}; }
Index索引注解可選參數(shù)
public @interface Index { //定義需要添加索引的字段 String[] value(); //定義索引的名稱 String name() default ""; //true-設(shè)置唯一鍵,標(biāo)識value數(shù)組中的索引字段必須是唯一的,不可重復(fù) boolean unique() default false; }
ForeignKey外鍵注解可選參數(shù)
public @interface ForeignKey { //引用外鍵的表的實(shí)體 Class entity(); //要引用的外鍵列 String[] parentColumns(); //要關(guān)聯(lián)的列 String[] childColumns(); //當(dāng)父類實(shí)體(關(guān)聯(lián)的外鍵表)從數(shù)據(jù)庫中刪除時執(zhí)行的操作 @Action int onDelete() default NO_ACTION; //當(dāng)父類實(shí)體(關(guān)聯(lián)的外鍵表)更新時執(zhí)行的操作 @Action int onUpdate() default NO_ACTION; //在事務(wù)完成之前,是否應(yīng)該推遲外鍵約束 boolean deferred() default false; //給onDelete,onUpdate定義的操作 int NO_ACTION = 1; int RESTRICT = 2; int SET_NULL = 3; int SET_DEFAULT = 4; int CASCADE = 5; @IntDef({NO_ACTION, RESTRICT, SET_NULL, SET_DEFAULT, CASCADE}) @interface Action { } }
定義Dao類
@Dao public interface StudentDao { @Query("SELECT * FROM StudentEntity") ListgetAll(); @Query("SELECT * FROM StudentEntity WHERE id IN (:ids)") List getAllByIds(long[] ids); @Insert void insert(StudentEntity... entities); @Delete void delete(StudentEntity entity); @Update void update(StudentEntity entity); }
@insert, @Update都可以執(zhí)行事務(wù)操作,定義在OnConflictStrategy注解類中
public @interface Insert { //定義處理沖突的操作 @OnConflictStrategy int onConflict() default OnConflictStrategy.ABORT; } public @interface OnConflictStrategy { //策略沖突就替換舊數(shù)據(jù) int REPLACE = 1; //策略沖突就回滾事務(wù) int ROLLBACK = 2; //策略沖突就退出事務(wù) int ABORT = 3; //策略沖突就使事務(wù)失敗 int FAIL = 4; //忽略沖突 int IGNORE = 5; }
定義數(shù)據(jù)庫
@Database(entities = {StudentEntity.class}, version = 1) public abstract class RoomDemoDatabase extends RoomDatabase { public abstract StudentDao studentDao(); }
生成數(shù)據(jù)庫實(shí)例
RoomDemoDatabase database = Room.databaseBuilder(getApplicationContext(), RoomDemoDatabase.class, "database_name") .build();
生成數(shù)據(jù)庫實(shí)例的其他操作
Room.databaseBuilder(getApplicationContext(), RoomDemoDatabase.class, "database_name") .addCallback(new RoomDatabase.Callback() { //第一次創(chuàng)建數(shù)據(jù)庫時調(diào)用,但是在創(chuàng)建所有表之后調(diào)用的 @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); } //當(dāng)數(shù)據(jù)庫被打開時調(diào)用 @Override public void onOpen(@NonNull SupportSQLiteDatabase db) { super.onOpen(db); } }) .allowMainThreadQueries()//允許在主線程查詢數(shù)據(jù) .addMigrations()//遷移數(shù)據(jù)庫使用,下面會單獨(dú)拿出來講 .fallbackToDestructiveMigration()//遷移數(shù)據(jù)庫如果發(fā)生錯誤,將會重新創(chuàng)建數(shù)據(jù)庫,而不是發(fā)生崩潰 .build();
數(shù)據(jù)庫遷移(升級)
Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name") .addMigrations(MIGRATION_1_2, MIGRATION_2_3).build(); static final Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(SupportSQLiteDatabase database) { database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, " + "`name` TEXT, PRIMARY KEY(`id`))"); } }; static final Migration MIGRATION_2_3 = new Migration(2, 3) { @Override public void migrate(SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE Book " + " ADD COLUMN pub_year INTEGER"); } };
創(chuàng)建嵌套對象
有時,您希望將一個實(shí)體或普通的以前的Java對象(POJO)作為數(shù)據(jù)庫邏輯中的一個完整的整體來表示,即使該對象包含幾個字段。在這些情況下,您可以使用@Embedded來表示一個對象,您希望將其分解為表中的子字段。然后可以像對其他單個列一樣查詢嵌入式字段
class Address { public String street; public String state; public String city; @ColumnInfo(name = "post_code") public int postCode; } @Entity class User { @PrimaryKey public int id; public String firstName; @Embedded public Address address; }
這樣user表中的字段就包含了 id , firstName , street , state , city , 和 post_code
注意 :嵌入式字段還可以包含其他嵌入式字段
如果一個實(shí)體具有相同類型的多個內(nèi)嵌字段,則可以通過設(shè)置前綴屬性(prefix)使每個列保持惟一。然后將所提供的值添加到嵌入對象中每個列名的開頭
@Embedded(prefix = "foo_") Coordinates coordinates;
和 LiveData 一起使用
添加依賴
// ReactiveStreams support for LiveData implementation "android.arch.lifecycle:reactivestreams:1.0.0"
修改返回類型
@Dao public interface MyDao { @Query("SELECT first_name, last_name FROM user WHERE region IN (:regions)") public LiveData> loadUsersFromRegionsSync(List
regions); }
和RxJava一起使用
添加依賴
// RxJava support for Room implementation "android.arch.persistence.room:rxjava2:1.0.0"
修改返回類型
@Dao public interface MyDao { @Query("SELECT * from user where id = :id LIMIT 1") public FlowableloadUserById(int id); }
直接游標(biāo)訪問
@Dao public interface MyDao { @Query("SELECT * FROM user WHERE age > :minAge LIMIT 5") public Cursor loadRawUsersOlderThan(int minAge); }
類型轉(zhuǎn)換
定義轉(zhuǎn)換類,@TypeConverter注解定義轉(zhuǎn)換的方法
public class Converters { @TypeConverter public static Date fromTimestamp(Long value) { return value == null ? null : new Date(value); } @TypeConverter public static Long dateToTimestamp(Date date) { return date == null ? null : date.getTime(); } }
@TypeConverters注解,告知數(shù)據(jù)庫要依賴哪些轉(zhuǎn)換類
@Database(entities = {User.class}, version = 1) @TypeConverters({Converters.class}) public abstract class AppDatabase extends RoomDatabase { public abstract UserDao userDao(); }
使用這些轉(zhuǎn)換器,您可以在其他查詢中使用您的自定義類型,正如您將使用基本類型一樣,如下代碼所示
@Entity public class User { ... private Date birthday; } @Dao public interface UserDao { ... @Query("SELECT * FROM user WHERE birthday BETWEEN :from AND :to") ListfindUsersBornBetweenDates(Date from, Date to); }
輸出模式
在編譯時,將數(shù)據(jù)庫的模式信息導(dǎo)出到JSON文件中,這樣可有利于我們更好的調(diào)試和排錯
build.gradle android { ... defaultConfig { ... javaCompileOptions { annotationProcessorOptions { arguments = ["room.schemaLocation": "$projectDir/schemas".toString()] } } } }
關(guān)于如何在Android中與Room組件問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。
文章題目:如何在Android中與Room組件-創(chuàng)新互聯(lián)
本文鏈接:http://ef60e0e.cn/article/dogiie.html