Android Room的使用詳解
官網(wǎng)介紹:developer.android.google.cn/training/da…
Room 是在 SQLite 上提供了一個抽象層,以便在充分利用 SQLite 的強大功能的同時,能夠流暢地訪問數(shù)據(jù)庫。
Room 包含 3 個重要部分:
數(shù)據(jù)庫:包含數(shù)據(jù)庫持有者,并作為應(yīng)用已保留的持久關(guān)系型數(shù)據(jù)的底層連接的主要接入點。 Entity:表示數(shù)據(jù)庫中的表。 DAO:包含用于訪問數(shù)據(jù)庫的方法。基本使用步驟:
1、導(dǎo)入配置dependencies { def room_version = '2.2.5' implementation 'androidx.room:room-runtime:$room_version' annotationProcessor 'androidx.room:room-compiler:$room_version' // For Kotlin use kapt instead of annotationProcessor // optional - Kotlin Extensions and Coroutines support for Room implementation 'androidx.room:room-ktx:$room_version' // optional - RxJava support for Room implementation 'androidx.room:room-rxjava2:$room_version' // optional - Guava support for Room, including Optional and ListenableFuture implementation 'androidx.room:room-guava:$room_version' // Test helpers testImplementation 'androidx.room:room-testing:$room_version' }2、創(chuàng)建表
@Entity public class User {@PrimaryKeypublic int uid;@ColumnInfo(name = 'first_name')public String firstName;@ColumnInfo(name = 'last_name')public String lastName; }
參考:developer.android.google.cn/training/da…
3、創(chuàng)建Dao包含訪問數(shù)據(jù)庫的一系列方法。
@Dao public interface UserDao {@Query('SELECT * FROM user')List<User> getAll();@Query('SELECT * FROM user WHERE uid IN (:userIds)')List<User> loadAllByIds(int[] userIds);@Query('SELECT * FROM user WHERE first_name LIKE :first AND ' + 'last_name LIKE :last LIMIT 1')User findByName(String first, String last);@Insertvoid insertAll(User... users);@Insertvoid insert(User user);@Deletevoid delete(User user); }
參考:developer.android.google.cn/training/da…
4、創(chuàng)建數(shù)據(jù)庫@Database(entities = {User.class}, version = 1) public abstract class AppDatabase extends RoomDatabase {public abstract UserDao userDao(); }5、使用
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, 'database-name').build(); db.userDao().insert(new User());
以上就是Android Room的使用詳解的詳細內(nèi)容,更多關(guān)于Android Room的使用的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. IntelliJ IDEA調(diào)整字體大小的方法2. 淺談JavaScript宏任務(wù)和微任務(wù)執(zhí)行順序3. PHP大文件分割分片上傳實現(xiàn)代碼4. 使用 kind 和 Docker 啟動本地的 Kubernetes環(huán)境5. Docker 容器健康檢查機制6. IntelliJ IDEA導(dǎo)入jar包的方法7. idea環(huán)境下Maven無法正常下載pom中配置的包問題8. python在CMD界面讀取excel所有數(shù)據(jù)的示例9. vue+elementUI下拉框回顯問題及解決方式10. 刪除docker里建立容器的操作方法

網(wǎng)公網(wǎng)安備