Room是Android Jetpack中的一个组件,它提供了一个抽象层,帮助开发者在本地数据库(如SQLite)上进行持久化数据存储。Room通过简化数据库操作,使得数据管理变得更加容易和高效。
Room重要的概念
- 实体(Entity):实体是用于表示数据库表的类。通过使用@Entity注解,可以定义一个实体类,并将其映射到数据库表。实体类中的属性对应于数据库表中的列。
- 数据库(Database):数据库类是一个抽象类,用于定义数据库版本和包含的实体。通过使用@Database注解,可以创建一个继承自RoomDatabase的抽象类,并指定实体类和数据库版本。
- 数据访问对象(DAO):DAO接口用于定义对数据库的访问操作。通过使用@Dao注解,可以定义一个接口,并在其中声明各种CRUD方法。这些方法会被转换为对应的SQL语句。
在Android开发中,使用DAO(Data Access Object)、Repository和ViewModel的架构模式是为了实现数据与界面的清晰分离,提高应用的可维护性和扩展性。
- DAO(Data Access Object):DAO是负责直接与数据库交互的组件。它定义了操作数据库的方法,如查询、插入、更新和删除。通过使用DAO,开发者可以将数据库操作逻辑从业务逻辑中分离出来,使得代码更加模块化和易于管理。
- Repository:Repository层作为数据源和ViewModel之间的中介,负责处理数据请求和响应。它可以封装多个数据源,例如本地数据库和远程API,并提供一个统一的接口供ViewModel调用。这样,当数据源发生变化时,只需要修改Repository层,而不必触及ViewModel或View层,从而提高了代码的复用性和可维护性。
- ViewModel:ViewModel是一个用于存储和管理UI相关数据的架构组件。它的主要目的是将UI控制器(如Activity和Fragment)与数据相关的业务逻辑分开,使得UI控制器能够专注于展示数据和响应用户交互,而数据的获取和处理则交由ViewModel来管理。这种分离能够使代码更加清晰、易于测试和维护。
案例:Room + ViewModel + LiveData 实现操作
使用步骤:
1.引入依赖
def room_version = "2.6.1"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
2.定义实体
@Entity(tableName = "student")
public class Student {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id",typeAffinity = ColumnInfo.INTEGER)
public int id;
@ColumnInfo(name = "name",typeAffinity = ColumnInfo.TEXT)
public String name;
@ColumnInfo(name = "age",typeAffinity = ColumnInfo.INTEGER)
public int age;
public Student(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
@Ignore
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Ignore
public Student(int id) {
this.id = id;
}
}
3.定义Dao
@Dao
public interface StudentDao {
@Insert
void insert(Student... students);
@Delete
void delete(Student... students);
@Update
void update(Student... students);
@Query("select * from student")
List<Student> getAllStudent();
@Query("select * from student where id = :id")
Student getStudentById(int id);
}
3.定义MyDatabase
@Database(entities = {Student.class}, version = 1,exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {
private static final String DB_NAME = "my_db.db";
private static MyDatabase mInstance;
public static synchronized MyDatabase getInstance(Context context){
if(mInstance == null){
mInstance = Room.databaseBuilder(context.getApplicationContext(),
MyDatabase.class,
DB_NAME
).build();
}
return mInstance;
}
public abstract StudentDao studentDao();
}
4.定义StudentRepository
public class StudentRepository {
private StudentDao studentDao;
public StudentRepository(Context context){
MyDatabase db = MyDatabase.getInstance(context);
studentDao = db.studentDao();
}
public void insert(Student... students){
new InsertStudentTask(studentDao).execute(students);
}
class InsertStudentTask extends AsyncTask<Student, Void,Void>{
private StudentDao studentDao;
public InsertStudentTask(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
protected Void doInBackground(Student... students) {
studentDao.insert(students);
return null;
}
}
public void update(Student... students){
new UpdateStudentTask(studentDao).execute(students);
}
class UpdateStudentTask extends AsyncTask<Student, Void,Void>{
private StudentDao studentDao;
public UpdateStudentTask(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
protected Void doInBackground(Student... students) {
studentDao.update(students);
return null;
}
}
public void delete(Student... students){
new DeleteStudentTask(studentDao).execute(students);
}
class DeleteStudentTask extends AsyncTask<Student, Void,Void>{
private StudentDao studentDao;
public DeleteStudentTask(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
protected Void doInBackground(Student... students) {
studentDao.delete(students);
return null;
}
}
public void deleteAllStudent(){
new DeleteAllStudentTask(studentDao).execute();
}
class DeleteAllStudentTask extends AsyncTask<Void, Void,Void>{
private StudentDao studentDao;
public DeleteAllStudentTask(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
protected Void doInBackground(Void... voids) {
studentDao.deleteAll();
return null;
}
}
public LiveData<List<Student>> getAllStudent(){
return studentDao.getAllStudent();
}
}
5.定义StudentViewModel
public class StudentViewModel extends AndroidViewModel {
private StudentRepository studentRepository;
public StudentViewModel(@NonNull Application application) {
super(application);
studentRepository = new StudentRepository(application);
}
public void insert(Student... students)
{
studentRepository.insert(students);
}
public void delete(Student... students)
{
studentRepository.delete(students);
}
public void deleteAllStudent(){
studentRepository.deleteAllStudent();
}
public void update(Student... students)
{
studentRepository.update(students);
}
public LiveData<List<Student>> getAllStudnet(){
return studentRepository.getAllStudent();
}
}
6.在MainActivity操作实现数据新增删除等操作
public class MainActivity extends AppCompatActivity {
private StudentRecyclerViewAdapter adapter;
private StudentViewModel studentViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<Student> studentList = new ArrayList<>();
adapter = new StudentRecyclerViewAdapter(studentList);
recyclerView.setAdapter(adapter);
studentViewModel = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory())
.get(StudentViewModel.class);
studentViewModel.getAllStudnet().observe(this, new Observer<List<Student>>() {
@Override
public void onChanged(List<Student> students) {
adapter.setStudentList(students);
adapter.notifyDataSetChanged();
}
});
}
public void mInsert(View view) {
Student s1 = new Student(18,"张三");
Student s2 = new Student(19,"李四");
studentViewModel.insert(s2);
studentViewModel.insert(s1);
}
public void mUpdate(View view) {
Student s1 = new Student(4,99,"新张三");
studentViewModel.update(s1);
}
public void mDelete(View view) {
Student s1 = new Student(2);
studentViewModel.delete(s1);
}
public void mClear(View view) {
studentViewModel.deleteAllStudent();
}
}