1、在build.gradle里引入room库依赖:
dependencies {
implementation 'androidx.room:room-runtime:2.2.5'
annotationProcessor 'androidx.room:room-compiler:2.2.5'
}
2、创建数据表类:
package com.example.experimentforsqlite.sqliteRoom.tables;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity//通过Entity接口来声明本类为表格类
public class Students {
@PrimaryKey(autoGenerate = true)//通过接口设置自增约束
@ColumnInfo(name="id")//设置属性字段名
private int id;
@ColumnInfo(name="student_name")
private String studentName;
@ColumnInfo(name="student_sex")
private String studentSex;
@ColumnInfo(name = "student_phone")
private String Phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
......
}
3、创建dao接口:
package com.example.experimentforsqlite.sqliteRoom.daos;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import com.example.experimentforsqlite.sqliteRoom.tables.Students;
import java.util.List;
@Dao//声明此为dao接口
public interface StudentDao {
@Insert//声明此为插入方法
void insertStudents(Students... students);
@Delete//声明此外删除方法
void deleteStudents(Students... students);
@Update//声明此外修改方法
void updateStudents(Students... students);
@Query("Delete FROM Students")//通过query类调用原生sql代码操作数据库
void clear();
@Query("SELECT * FROM Students")
LiveData<List<Students>> queryAll();
@Query("SELECT * FROM students WHERE student_name LIKE :str OR student_phone LIKE :str OR student_phone LIKE :str ORDER BY id DESC")
LiveData<List<Students>> queryWithWordsLive(String str);
@Query("SELECT * FROM students WHERE student_name LIKE :str OR student_phone LIKE :str OR student_phone LIKE :str ORDER BY id DESC")
List<Students> queryWithWords(String str);
}
4、创建数据库类继承room数据库的基类:
package com.example.experimentforsqlite.sqliteRoom.database;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import com.example.experimentforsqlite.sqliteRoom.daos.StudentDao;
import com.example.experimentforsqlite.sqliteRoom.tables.Students;
@Database(entities = {Students.class},version = 1,exportSchema = false)
//声明此外数据库类,entities对应要操作的表们
public abstract class UseRoomDatabase extends androidx.room.RoomDatabase {
private static UseRoomDatabase INSTANCE;//声明单例对象,减小数据库开销
private static final String DATABASE_NAME="room_database_test";
public static UseRoomDatabase getINSTANCE(Context context) {//通过单例对象获取数据库
if(INSTANCE==null){
INSTANCE= Room.databaseBuilder(context,UseRoomDatabase.class,DATABASE_NAME)
//.addMigrations(MIGRATION_1_2)更新数据库
.build();
}
return INSTANCE;
}
public abstract StudentDao getStudentDao();//创建抽象的dao方法以便获取dao对象
/*static Migration MIGRATION_1_2=new Migration(1,2) {//数据库迁移
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE WORDS ADD COLUMN COL_NAME INTEGER NOT NULL DEFAULT 1");
}
};*/
}
5、由于使用规范,所以我们需创建一个repository仓库类来对数据库数据进行操作,其中,由于需要使用异步实现,所以我们创建内部类来继承AsyncTask类以实现异步效果。
package com.example.experimentforsqlite.sqliteRoom.repositories;
import android.content.Context;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.example.experimentforsqlite.sqliteRoom.daos.StudentDao;
import com.example.experimentforsqlite.sqliteRoom.database.UseRoomDatabase;
import com.example.experimentforsqlite.sqliteRoom.tables.Students;
import java.util.List;
public class StudentRepository {
private UseRoomDatabase database;
private StudentDao dao;
public StudentRepository(Context context) {
database=UseRoomDatabase.getINSTANCE(context);
dao=database.getStudentDao();
}
public LiveData<List<Students>> queryAll(){
return dao.queryAll();
}
public LiveData<List<Students>> queryWithWordsLive(String str){
return dao.queryWithWordsLive(str);
}
public List<Students> queryWithWords(String str){
return dao.queryWithWords(str);
}
public void insert(Students... students){
new InsertAsyncTask(dao).execute(students);//通过该语句来调用异步方法
}
public void update(Students... students){
new UpdateAsyncTask(dao).execute(students);//通过该语句来调用异步方法
}
public void delete(Students... students){
new DeleteAsyncTask(dao).execute(students);//通过该语句来调用异步方法
}
public void clear(){
new ClearAsyncTask(dao).execute();
}
static class InsertAsyncTask extends AsyncTask<Students,Void,Void>{
public StudentDao dao;
public InsertAsyncTask(StudentDao dao) {
this.dao = dao;
}
@Override
protected Void doInBackground(Students... students) {
dao.insertStudents(students);
return null;
}
}
static class UpdateAsyncTask extends AsyncTask<Students,Void,Void>{//Students为传入的实例类型
public StudentDao dao;
public UpdateAsyncTask(StudentDao dao) {
this.dao = dao;
}
@Override
protected Void doInBackground(Students... students) {//异步后台执行
dao.updateStudents(students);
return null;
}
}
static class DeleteAsyncTask extends AsyncTask<Students,Void,Void>{
public StudentDao dao;
public DeleteAsyncTask(StudentDao dao) {
this.dao = dao;
}
@Override
protected Void doInBackground(Students... students) {
dao.deleteStudents(students);
return null;
}
}
static class ClearAsyncTask extends AsyncTask<Void,Void,Void>{//用Viod来放入无参的方法
public StudentDao dao;
public ClearAsyncTask(StudentDao dao) {
this.dao = dao;
}
@Override
protected Void doInBackground(Void... voids) {
dao.clear();
return null;
}
}
}
6、通过ViewModel来获取数据:
package com.example.experimentforsqlite.sqliteRoom.viewModels;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.example.experimentforsqlite.sqliteRoom.repositories.StudentRepository;
import com.example.experimentforsqlite.sqliteRoom.tables.Students;
import java.util.List;
public class StudentViewModel extends AndroidViewModel {
private StudentRepository repository;
public StudentViewModel(@NonNull Application application) {
super(application);
repository=new StudentRepository(application);
}
public LiveData<List<Students>> queryAll(){
return repository.queryAll();
}
public LiveData<List<Students>> queryWithWordsLive(String str){
return repository.queryWithWordsLive(str);
}
public List<Students> queryWithWords(String str){
return repository.queryWithWords(str);
}
public void clear(){
repository.clear();//调用respository里的方法
}
public void delete(Students... students){
repository.delete(students);
}
public void insert(Students... students){
repository.insert(students);
}
public void update(Students... students){
repository.update(students);
}
}
7、活动里直接声明viewModel使用就好:
package com.example.experimentforsqlite.sqliteRoom;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.example.experimentforsqlite.adapters.RecyclerViewAdapterOne;
import com.example.experimentforsqlite.databinding.ActivitySqliteRoomMainBinding;
import com.example.experimentforsqlite.sqliteRoom.tables.Students;
import com.example.experimentforsqlite.sqliteRoom.viewModels.StudentViewModel;
import java.util.List;
public class SqliteRoomMain extends AppCompatActivity {
private ActivitySqliteRoomMainBinding binding;
private LiveData<List<Students>> dataLive;
private RecyclerViewAdapterOne adapter;
private StudentViewModel viewModel;
private List<Students> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel= new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(StudentViewModel.class);
binding=ActivitySqliteRoomMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
initView();
}
private void initView(){
dataLive=viewModel.queryAll();
binding.recyclerView1.setLayoutManager(new LinearLayoutManager(this));
dataLive.observe(this, new Observer<List<Students>>() {
@Override
public void onChanged(List<Students> students) {
data=students;
adapter=new RecyclerViewAdapterOne(data);
binding.recyclerView1.setAdapter(adapter);
}
});
binding.buttonInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SqliteRoomMain.this,InsertMainForRoom.class));
}
});
}
//直接使用viewModel对象的方法即可。
private void update(Students... students){
viewModel.update(students);
}
private void clear(){
viewModel.clear();
}
private void delete(Students... students){
viewModel.delete(students);
}
}
room数据库使用总结:
????????分别建数据表、数据表对应的Dao操作接口、数据库继承room基类数据库,由于通过异步来实现请求,所以我们需要设置仓库类来单独处理,在其内部添加异步实现类来完成异步操作,最后通过ViewModel来临时保存数据,活动类通过使用viewModel对象可实现对应的增删改查。
? ? ? ? 这样room数据库就可以实现其高效和维护性高的特性了。
学到了,哈哈!
|