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)文章:
