Room组件的用法

一.Android官方ORM数据库Room

  Android采用Sqlite作为数据库存储。但由于Sqlite代码写起来繁琐且容易出错,因此Google推出了Room,其实Room就是在Sqlite上面再封装了一层。下面是Room的架构图:

      Room组件的用法

  要想更好地理解上面的图,我们先要理解几个概念:Entity和Dao

  Entity:实体,一个entity就对应于数据库中的一张表。Entity类是Sqlite中的表对java类的映射,例如有一个学生表,有id,name,age三个字段;那么对应的就有一个学生类,有id,name,age三个成员变量和学生表中的字段进行一一对应。

  Dao:即Data Access Object,数据访问对象,就是字面意思,可以通过他来访问数据库中的数据。

  那么所谓的ORM(Object Relational Mapping),对象关系映射,就很好理解了。就是建立一个从数据库表到java类的映射,表中的字段对应类中的成员变量,表中的记录对应该类的一个实例。

二.Room数据库的基本使用方法

  1.在使用Room数据库前,先要在app/build.gradle文件中导入以下的依赖:

  implementation 'androidx.room:room-runtime:2.5.2'
  annotationProcessor 'androidx.room:room-compiler:2.5.2'
 2.创建一个关于学生的Entity,即创建一张学生表:

@Entity
public class Student {
@PrimaryKey
private Integer id;
@ColumnInfo(name="name",typeAffinity = ColumnInfo.TEXT)
private String name;
@ColumnInfo(name="age",typeAffinity = ColumnInfo.INTEGER)
private Integer age;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
'}';
}
}
 

  @Entity注解用于将Student类和Room数据库中的数据表对应起来;@PrimaryKey注解即主键约束;@ColumnInfo注解可以设置该成员变量对应的表中字段的名称以及类型

  需要注意的一点是get方法不可省略

  3.针对上面的学生类Entity,我们需要定义一个Dao接口文件,以便对数据库进行访问,在接口的上方加上@Dao注解即可

@Dao public interface StudentDao {     @Insert     void insertStudent(Student student);     @Delete     void deleteStudent(Student student);     @Update     void updataStudent(Student student);     @Query("select * from Student")     LiveData<List<Student>> getAllStudents();     @Query("select * from student where id=:id")     Student selectStudentById(Integer id); }

  4.定义好Entity和Dao后,接下来就是创建数据库了,代码如下:

@Database(entities = {Student.class},version = 1) public abstract class MyDatabase extends RoomDatabase {     private static final String DATABASE_NAME="my_db";     private static MyDatabase myDatabase;     public static synchronized MyDatabase getInstance(Context context){         if(myDatabase==null){             myDatabase= Room.databaseBuilder(context,MyDatabase.class,DATABASE_NAME).build();         }         return myDatabase;     }     @Override     public void clearAllTables() {      }      @NonNull     @Override     protected InvalidationTracker createInvalidationTracker() {         return null;     }      @NonNull     @Override     protected SupportSQLiteOpenHelper createOpenHelper(@NonNull DatabaseConfiguration databaseConfiguration) {         return null;     }     public abstract StudentDao studentDao(); }

  @Database注解用于告诉系统这是Room数据库对象,entities属性用于指定该数据库有哪些表,version用于指定数据库的版本号

  数据库类需要继承RoomDatabase类,并结合单例模式完成创建。

  到这里,数据库和表就创建完成了,接下来就看看如何对数据库进行增删改查了。

  5.结合ViewModel和LiveData,对数据库进行增删改查,并且数据库表的记录发生变化时,页面可以及时收到通知,并更新页面。

  LiveData通常和ViewModel一起使用,ViewModel用于存储页面的数据,因此我们可以把数据库的实例化放到ViewModel中,但数据库的实例化需要用到Context对象,因此我们不宜直接用ViewModel,而应该用其子类AndroidViewModel。  

public class StudentViewModel extends AndroidViewModel {     private MyDatabase myDatabase;     private LiveData<List<Student>> liveDataStudents;      public StudentViewModel(@NonNull Application application) {         super(application);         myDatabase=MyDatabase.getInstance(application);         liveDataStudents=myDatabase.studentDao().getAllStudents();     }     public LiveData<List<Student>> getLiveDataStudents(){         return liveDataStudents;     }     public void insertStudent(Student student){         myDatabase.studentDao().insertStudent(student);     }     public void deleteStudent(Student student){         myDatabase.studentDao().deleteStudent(student);     }     public void updateStudent(Student student){         myDatabase.studentDao().updataStudent(student);     }     public Student selectStudentById(Integer id){         return myDatabase.studentDao().selectStudentById(id);     } }

  6.在Activity中实例化StudentViewModel,并进行增删改查操作,并监听LiveData的变化。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {     private Button btn_insert,btn_delete,btn_update,btn_select;     private TextView tv_display;     private StudentViewModel studentViewModel;     private ExecutorService executor = Executors.newSingleThreadExecutor();     private Student student;     @SuppressLint("MissingInflatedId")     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         tv_display=findViewById(R.id.tv_display);         btn_delete=findViewById(R.id.btn_delete);         btn_insert=findViewById(R.id.btn_insert);         btn_update=findViewById(R.id.btn_update);         btn_select=findViewById(R.id.btn_select);         btn_select.setOnClickListener(this);         btn_insert.setOnClickListener(this);         btn_delete.setOnClickListener(this);         btn_update.setOnClickListener(this);         studentViewModel=new ViewModelProvider(this,new MyViewModelFactory(getApplication())).get(StudentViewModel.class);         studentViewModel.getLiveDataStudents().observe(this, new Observer<List<Student>>() {             @Override             public void onChanged(List<Student> students) {                 tv_display.setText(students+"");             }         });     }      @Override     public void onClick(View view) {         switch(view.getId()){             case R.id.btn_delete:                 executor.execute(new Runnable() {                     @Override                     public void run() {                         studentViewModel.deleteStudent(new Student(1,"jack",20));                     }                 });                 break;             case R.id.btn_update:                 executor.execute(new Runnable() {                     @Override                     public void run() {                         studentViewModel.updateStudent(new Student(1,"zhangsan",32));                     }                 });                  break;             case R.id.btn_insert:                 executor.execute(new Runnable() {                     @Override                     public void run() {                         studentViewModel.insertStudent(new Student(1,"lisi",22));                     }                 });                 break;             case R.id.btn_select:                 executor.execute(new Runnable() {                     @Override                     public void run() {                         student = studentViewModel.selectStudentById(1);                         Log.i("test",student.toString());                     }                 });                 break;         }     } }

public class MyViewModelFactory implements ViewModelProvider.Factory {     private Application application;     public MyViewModelFactory(Application application){         this.application=application;     }     @NonNull     @Override     public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {         return (T)new StudentViewModel(application);     } }

  运行应用程序,对数据库进行增删改操作时,onChanged方法就会回调,然后在这个方法中对页面进行更新即可。

 

发表评论

评论已关闭。

相关文章