Android Room的使用詳解
官網(wǎng)介紹:developer.android.google.cn/training/da…
Room 是在 SQLite 上提供了一個抽象層,以便在充分利用 SQLite 的強(qiáng)大功能的同時,能夠流暢地訪問數(shù)據(jù)庫。
Room 包含 3 個重要部分:
數(shù)據(jù)庫:包含數(shù)據(jù)庫持有者,并作為應(yīng)用已保留的持久關(guān)系型數(shù)據(jù)的底層連接的主要接入點(diǎn)。 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的使用詳解的詳細(xì)內(nèi)容,更多關(guān)于Android Room的使用的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 理解PHP5中static和const關(guān)鍵字2. Android table布局開發(fā)實(shí)現(xiàn)簡單計算器3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. IntelliJ IDEA安裝插件的方法步驟5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. vue 使用localstorage實(shí)現(xiàn)面包屑的操作7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫使用方法及異常處理方案9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

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