Android Jetpack中Room的使用
Room
Room主要分三個(gè)部分 database、dao和實(shí)體類entity
Entity
entity實(shí)體類定義時(shí)需要用到@Entity(tableName = "student")注解,其中參數(shù)為表名
主鍵定義需要用到@PrimaryKey(autoGenerate = true)注解,參數(shù)決定是否自增長(zhǎng)
每個(gè)屬性(也就是表的字段)都需要加@ColumnInfo(name = "name",typeAffinity = ColumnInfo.TEXT)注解 ,name是表中的字段名、 typeAffinity是字段類型,類型有:
// 未定義類型關(guān)聯(lián)。將基于類型進(jìn)行解析。 int UNDEFINED = 1; // 文本類型 int TEXT = 2; // 整數(shù)或布爾值的列關(guān)聯(lián)常數(shù)。 int INTEGER = 3; // 用于浮點(diǎn)數(shù)或雙精度數(shù)的列關(guān)聯(lián)常數(shù)。 int REAL = 4; // 二進(jìn)制數(shù)據(jù)的列親和常數(shù)。 int BLOB = 5;
實(shí)體類需要指定一個(gè)構(gòu)造方法。如果我們有多個(gè)構(gòu)造方法,那么就需要告訴room忽略其他的構(gòu)造器,不然會(huì)報(bào)錯(cuò),room只可以使用一個(gè)構(gòu)造器。構(gòu)造函數(shù)上加入@Ignore注解即可(想忽略一個(gè)屬性也是)
@Entity(tableName = "student")
public class Student {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id",typeAffinity = ColumnInfo.INTEGER)
public int id;
@ColumnInfo(name = "name",typeAffinity = ColumnInfo.TEXT)
public String name;
@ColumnInfo(name = "age",typeAffinity = ColumnInfo.INTEGER)
public int age;
@ColumnInfo(name = "sex",typeAffinity = ColumnInfo.INTEGER)
public int sex;
@Ignore// 告訴room忽略這個(gè)構(gòu)造方法
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Ignore// 告訴room忽略這個(gè)構(gòu)造方法
public Student(int id) {
this.id = id;
}
// 指定room用的構(gòu)造方法
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Dao
dao是一個(gè)interface,需要加入一個(gè)@Dao注解,內(nèi)部主要聲明一些對(duì)數(shù)據(jù)做操作的抽象方法,方法都需要加上room中特定的注解
@Insert 添加
@Update 修改
@Delete 刪除
@Query 查詢 此注解需要加入?yún)?shù) 參數(shù)就是sql語(yǔ)句
@Dao
public interface StudentDao {
@Insert
void insertStudent(Student...students);
@Query("SELECT * FROM student")
List<Student> getAllStudent();
@Query("SELECT * FROM student WHERE id=:id")
List<Student> getAllStudentById(int id);
@Query("DELETE FROM student")
void clearAll();
@Update
void upData(Student...students);
@Delete
void delete(Student...students);
}
DataBase
database類需要繼承RoomDatabase這個(gè)抽象類,dataBase也必須是抽象類。需要加入@DataBase注解
@Database(entities =
{Student.class}, version = 1, exportSchema = false) // entities-實(shí)體類 version-數(shù)據(jù)庫(kù)版本 exportSchema-是否生成schema文件,schema文件中包含的是表結(jié)構(gòu)和信息
如果想生成schema文件 還需要在build.gradle中指定schema文件的生成位置
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.room"
minSdkVersion 20
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
//指定room.schemaLocation生成的文件路徑
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
}
database類需要是單例的 但是不需要寫(xiě)私有構(gòu)造器,繼承了RoomDatabase之后room會(huì)識(shí)別,只需要一個(gè)getInstance方法,內(nèi)部是database的實(shí)例化。
public static synchronized StudentDataBase getInstance(Context context) {
if (mInstance == null) {
mInstance = Room.databaseBuilder(context.getApplicationContext(),
StudentDataBase.class,
DATABASE_NAME)
// .allowMainThreadQueries()// 允許在主線程操作數(shù)據(jù)庫(kù)
.addMigrations(MIGRATION_1_2)// 數(shù)據(jù)庫(kù)升級(jí)時(shí)
.fallbackToDestructiveMigration()// 數(shù)據(jù)庫(kù)版本異常時(shí) 會(huì)清空原來(lái)的數(shù)據(jù) 然后轉(zhuǎn)到目前版本
// .createFromAsset("資源文件中的初始數(shù)據(jù)庫(kù)")// 預(yù)填充數(shù)據(jù)庫(kù) 初始數(shù)據(jù)
.build();
}
return mInstance;
}
還需要聲明一個(gè)獲取dao的抽象方法,只聲明即可。
public abstract StudentDao getStudentDao();
當(dāng)數(shù)據(jù)庫(kù)的版本有升級(jí)時(shí),就需要使用到Migration,創(chuàng)建Migration(),參數(shù)為哪個(gè)版本到哪個(gè)版本的升級(jí)。重寫(xiě)mingrate方法,在mingrate方法內(nèi)通過(guò)database.execSQL()方法來(lái)寫(xiě)表的變化(結(jié)構(gòu)變化等)。Migration可以有多個(gè),對(duì)應(yīng)表的多次升級(jí)。
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE student ADD COLUMN sex INTEGER NOT NULL DEFAULT 1");// 添加表字段
}
};
database全貌
@Database(entities = {Student.class}, version = 1, exportSchema = true)
public abstract class StudentDataBase extends RoomDatabase {
private static StudentDataBase mInstance;
private static final String DATABASE_NAME = "student.db";
public static synchronized StudentDataBase getInstance(Context context) {
if (mInstance == null) {
mInstance = Room.databaseBuilder(context.getApplicationContext(),
StudentDataBase.class,
DATABASE_NAME)
// .allowMainThreadQueries()// 允許在主線程操作數(shù)據(jù)庫(kù)
.addMigrations(MIGRATION_1_2)// 數(shù)據(jù)庫(kù)升級(jí)時(shí)
.fallbackToDestructiveMigration()// 數(shù)據(jù)庫(kù)版本異常時(shí) 會(huì)清空原來(lái)的數(shù)據(jù) 然后轉(zhuǎn)到目前版本
// .createFromAsset("資源文件中的初始數(shù)據(jù)庫(kù)")// 預(yù)填充數(shù)據(jù)庫(kù) 初始數(shù)據(jù)
.build();
}
return mInstance;
}
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE student ADD COLUMN sex INTEGER NOT NULL DEFAULT 1");// 添加表字段
}
};
public abstract StudentDao getStudentDao();
}
使用
獲取dao
StudentDataBase dataBase = StudentDataBase.getInstance(this); StudentDao studentDao = dataBase.getStudentDao();
通過(guò)dao操作表,注意對(duì)數(shù)據(jù)庫(kù)的操作需要放到子線程中操作
class GetAllStudentTask extends AsyncTask<Void,Void,List<Student>>{
@Override
protected List<Student> doInBackground(Void... voids) {
List<Student> allStudent = studentDao.getAllStudent();
for (int j = 0; j < allStudent.size(); j++) {
Log.i("student", "doInBackground: "+allStudent.get(j).name+"--id:"+allStudent.get(j).id);
}
return allStudent;
}
到此這篇關(guān)于Jetpack中Room的使用的文章就介紹到這了,更多相關(guān)Jetpack中Room使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android自定義view實(shí)現(xiàn)進(jìn)度條指示效果
這篇文章主要為大家詳細(xì)介紹了Android自定義view實(shí)現(xiàn)進(jìn)度條指示效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
Android 不同Activity間數(shù)據(jù)的傳遞 Bundle對(duì)象的應(yīng)用
本篇文章小編為大家介紹,Android 不同Activity間數(shù)據(jù)的傳遞 Bundle對(duì)象的應(yīng)用。需要的朋友參考下2013-04-04
自定義滑動(dòng)按鈕為例圖文剖析Android自定義View繪制
這篇文章主要介紹了自定義滑動(dòng)按鈕的例子,圖文剖析Android自定義View繪制,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-03-03
Android畫(huà)圖實(shí)現(xiàn)MPAndroidchart折線圖示例詳解
這篇文章主要為大家介紹了Android畫(huà)圖實(shí)現(xiàn)MPAndroidchart折線圖示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Android單一實(shí)例全局可調(diào)用網(wǎng)絡(luò)加載彈窗
這篇文章主要為大家詳細(xì)介紹了Android單一實(shí)例全局可調(diào)用網(wǎng)絡(luò)加載彈窗,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12
android廣角相機(jī)畸變校正算法和實(shí)現(xiàn)示例
今天小編就為大家分享一篇android廣角相機(jī)畸變校正算法和實(shí)現(xiàn)示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
Android如何實(shí)現(xiàn)社交應(yīng)用中的評(píng)論與回復(fù)功能詳解
目前,各種App的社區(qū)或者用戶曬照片、發(fā)說(shuō)說(shuō)的地方,都提供了評(píng)論功能,為了更好地學(xué)習(xí),自己把這個(gè)功能實(shí)現(xiàn)了一下,下面這篇文章主要給大家介紹了關(guān)于Android如何實(shí)現(xiàn)社交應(yīng)用中的評(píng)論與回復(fù)功能的相關(guān)資料,需要的朋友可以參考下2018-07-07
Android基于ImageView繪制的開(kāi)關(guān)按鈕效果示例
這篇文章主要介紹了Android基于ImageView繪制的開(kāi)關(guān)按鈕效果,結(jié)合實(shí)例形式分析了Android使用ImageView進(jìn)行按鈕繪制的界面布局、功能實(shí)現(xiàn)及相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-03-03
Android直播軟件搭建之實(shí)現(xiàn)背景顏色滑動(dòng)漸變效果的詳細(xì)代碼
這篇文章主要介紹了Android直播軟件搭建之實(shí)現(xiàn)背景顏色滑動(dòng)漸變效果的詳細(xì)代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09

