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的使用詳解的詳細(xì)內(nèi)容,更多關(guān)于Android Room的使用的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項目的過程2. ASP中常用的22個FSO文件操作函數(shù)整理3. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯誤頁的問題4. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp5. 三個不常見的 HTML5 實用新特性簡介6. ASP編碼必備的8條原則7. SharePoint Server 2019新特性介紹8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析
