Room简单使用
Room是一个持久性数据库,Room持久层库在SQLite上提供了一个抽象层,以便充分利用SQLite的强大功能同时,能够流畅地访问数据库,具有以下优势:
- 针对SQL查询的编译时验证
- 可最大限度减少重复和容易出错的样板代码的方便注解
- 简化了数据库迁移路径
Room的三个部分
- 数据库:用于保存数据库,并作为应用持久性数据底层连接的主要访问
- 数据实体:用于表示数据库中的表
- 数据访问对象(DAO):用于增删改查的数据方法
添加依赖
dependencies {
def room_version = "2.4.2"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-rxjava2:$room_version"
implementation "androidx.room:room-rxjava3:$room_version"
implementation "androidx.room:room-guava:$room_version"
testImplementation "androidx.room:room-testing:$room_version"
implementation "androidx.room:room-paging:2.5.0-alpha01"
}
创建数据实体-即数据表
- @Entity(tableName = “表名”):设置表名
- @PrimaryKey(autoGenerate = false):当设置为true,让sqlite生成唯一的ID(即添加一个主键)
- @Entity(primaryKeys = {“username”, “age”}):添加多个主键
- @Ignore:忽略某个字段
@Entity
public class User {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "username")
public String username;
@ColumnInfo(name = "age")
public int age;
@Ignore
Bitmap image;
}
注意:SQLite的表名和列名不区分大小写
创建数据访问对象(DAO)-即访问数据库的方法
- @DAO:指定数据访问对象
- @Insert:插入数据
- @Delete:删除数据
- @Update:更新数据
- @Query:查询数据
@Dao
public interface UserDao {
@Insert
void insert(User user);
@Delete
void delete(User user);
@Update
void update(User user);
@Query("select * from user")
List<User> getUserAll();
@Query("select * from user where username = :username and age = :age")
List<User> getUserInfo(String username, int age);
}
创建数据库类
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
创建并使用
AppDatabase database = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "test.db").build();
UserDao userDao = database.userDao();
List<User> userDataAll = userDao.getUserAll();
for (User user : userDataAll) {
Log.e("TAG", "id: " + user.id);
Log.e("TAG", "username: " + user.username);
Log.e("TAG", "age: " + user.age);
}
|