Android的Jetpack组件中Room的基础使用方法资源

Jetpack架构组件之 Room 入门 + 原理

介绍 :
Room 是Google为了简化旧式的SQLite操作专门提供的一个覆盖SQLite抽象层框架库
作用:
1.实现SQLite的增、删、查、改功能。
2.使用简单(类似于Retrofit库),通过注解的方式实现相关功能。
3.拥有SQLite的所有操作功能(表所有操作、版本升级…)。

基本使用方法

注解的力量:
1.Bean(实体)
@Entity : 数据表的实体类。
@PrimaryKey : 每一个实体类都需要一个唯一的标识。
@ColumnInfo : 数据表中字段名称。
@Ignore : 标注不需要添加到数据表中的属性。
@Embedded : 实体类中引用其他实体类。
@ForeignKey : 外键约束。

@Entity
public class Student {
    @PrimaryKey(autoGenerate = true)
    private int uid;
    @ColumnInfo(name = "name")
    private String name;
    @Ignore
    private String waihao
}

@Embedded JavaBean中含有复杂对象

@Entity
public class Person {
    @PrimaryKey
    private int name;
    @Embedded
    private Person person;
}
public class Person {
    private int nameIndex;
    private int ageIndex;
    @ColumnInfo(name = "address")
    private String address;
    }

使用对象封装多个属性

2.Database(数据库持久化)
@Database : 标注数据库持久化的类
entities 指定数据库对应的JaveBean对象集合,分号分开。
version 数据库版本
exportSchema false 数据库update时会使用
增加抽象函数返回数据库操作层Dao层,便于数据库的增删改查

@Database(entities = {Student.class,...}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    public abstract StudentDao studentDao();
}

错误提示:是由于数据库version不变,但是数据库字段变化
Room cannot verify the data integrity. Looks like you’ve changed schema but forgot to update the version number. You can simply fix this by increasing the version number.

3.Dao层: 数据库操作接口 (增加删改查)

@Dao
public interface StudentDao {
    @Insert
    void insert(Student student);
    @Delete
    void delete(Student student);
    @Update
    void update(Student student);
    @Query("select * from Student")
    List<Student> getAll();
}

查询:

@Query("select * from Student")
    List<Student> getAll();
//查询一条记录 参数为查询条件
 @Query("select * from Student where name like :name")
 Student findByName(String name);
 //返回集合
  @Query("SELECT first_name, last_name FROM user WHERE region IN (:regions)")
    public List<NameTuple> loadUsersFromRegions(List<String> regions);

使用:
Build文件中导入依赖

def room_version = "2.0.0-beta01"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version" // use kapt for Kotlin
    // 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"

    //ViewModel
    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
//Room通过 databaseBuilder的build获取Dao层,进行增删改查
 AppDatabase appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "studentDB").build();
        dao = appDatabase.studentDao();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Student student = new Student("lff", 1, 1);
                Person person = new Person(4,6,"plm");
                person.setAddress("abcdefd");
                student.setPerson(person);
                dao.insert(student);

                List<Student> students = dao.getAll();
                Log.i("lff", "size: "+students.size());
                if (students.size() > 0) {
                    String  name = students.get(0).getName();
                    TextView name1 = findViewById(R.id.name);
                    name1.setText(students.get(0).getPerson().getAddress());
                }
            }
        }).start();

原理说明:

AppDatabase appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "studentDB").build();
        dao = appDatabase.studentDao();
        //RoomDataBase.java  通过databaseBuilder

在这里插入图片描述
数据库的创建实现
在这里插入图片描述

RoomDatabase.java
public void init(@NonNull DatabaseConfiguration configuration) {
        mOpenHelper = createOpenHelper(configuration);//实际调用的为 AppDatabase_Impl自动生成类的 createOpenHelper函数
        
//AppDatabase_Impl.java 是RoomDatabase的实现类
//创建SupportSQLiteOpenHelper.Callback 的实例并重写方法
//在onCreate()中Sql语句创建student表
//在dropAllTables()中创建删除数据库的SQL语句
//在validateMigration()中完成数据库的升级

AppDatabase_Impl.java
    public AppDatabase_Impl() {
    }

    protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) {
        Callback _openCallback = new RoomOpenHelper(configuration, new Delegate(1) {
            public void createAllTables(SupportSQLiteDatabase _db) {
                _db.execSQL("CREATE TABLE IF NOT EXISTS `Student` (`uid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT, ;
            }
             protected void onCreate(SupportSQLiteDatabase _db) {
                if (AppDatabase_Impl.this.mCallbacks != null) {
                    int _i = 0;

                    for(int _size = AppDatabase_Impl.this.mCallbacks.size(); _i < _size; ++_i) {
                        ((androidx.room.RoomDatabase.Callback)AppDatabase_Impl.this.mCallbacks.get(_i)).onCreate(_db);
                    }
                }

            }

            public void onOpen(SupportSQLiteDatabase _db) {
                AppDatabase_Impl.this.mDatabase = _db;
                AppDatabase_Impl.this.internalInitInvalidationTracker(_db);
                i....
            }

            protected void validateMigration(SupportSQLiteDatabase _db) {
                HashMap<String, Column> _columnsStudent = new HashMap(7);
                ......
        return _helper;

数据库的操作接口

通过注解生成 StudentDao_Impl

public final class StudentDao_Impl implements StudentDao {
    private final RoomDatabase __db;// 传入的数据库
    private final EntityInsertionAdapter __insertionAdapterOfStudent;// 处理insert方法
    private final EntityDeletionOrUpdateAdapter __deletionAdapterOfStudent;// 删除insert方法
    private final EntityDeletionOrUpdateAdapter __updateAdapterOfStudent;// 更新insert方法

此Room的使用和源码执行流程就到此结束了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值