Android Room学习

 目录

Room三角色介绍

Room三角色编写

Room的实战


Room是SQLite数据库的抽象封装,可以让我们流畅易用的访问数据库

Room三角色介绍

Entity、Dao、DB

@Entity //完成对表的操作
class Student{}

@Dao //可以完成对上面表的crud(对数据库的增删改查)
class StudentDao{}

@Database(数据库名字,版本号) //数据信息
class StudentDB{}

Room三角色编写

引入依赖

implementation 'androidx.room:room-runtime:2.4.3'
annotationProcessor 'androidx.room:room-compiler:2.4.3'

编写三角色

Student.java

package com.example.myproject.room;
import androidx.room.Entity;
import androidx.room.PrimaryKey;


/**
 * 一张表 (主键唯一 主键自动增长, name,age)
 */
@Entity
public class Student {

    @PrimaryKey(autoGenerate = true)//主键id
    private int id;

    private String name;

    private int age;

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


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

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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


}

StudentDAO.java

package com.example.myproject.room;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;


/**
 * 可以完成对表的crud(对数据库的增删改查)
 */
@Dao
public interface StudentDAO {

    // 增
    @Insert
    void insertStudents(Student ...  students);

    // 改
    @Update
    void updateStudents(Student ... students);

    // 删  条件
    @Delete
    void deleteStudents(Student ... students);

    // 删除 所有     @Delete 单个条件删除用的
    @Query("DELETE FROM Student")
    void deleteAllStudents();

    // 查询 所有  倒序 查询
    @Query("SELECT * FROM Student ORDER BY ID DESC")
    List<Student> getAllStudent();

}

StudentDatabase.java

package com.example.myproject.room;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

/**
 * 数据库 关联
 */
@Database(entities = {Student.class},version = 1,exportSchema = false)
public abstract  class StudentDatabase extends RoomDatabase {

    //StudentDAO
    public abstract StudentDAO getStudentDao();

    //StudentDatabase
    private static StudentDatabase INSTANCE;

    public static synchronized StudentDatabase getInstance(Context context){
        if(INSTANCE == null){
            INSTANCE = Room.databaseBuilder(
                            context.getApplicationContext(),StudentDatabase.class,"dl")
                    //默认异步线程
                    //.allowMainThreadQueries()
                    .build();
        }

        return INSTANCE;
    }

}

Room的实战

用户只需要拿DAO

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity4"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="插入"
        android:onClick="insertAction"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改"
        android:onClick="updateAction"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除"
        android:onClick="deleteAction"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询"
        android:onClick="queryAction"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="全部删除"
        android:onClick="deleteAllAction"
        />
</LinearLayout>

Student.java、StudentDatabase.java、StudentDao.java同上(角色编写)

DBEngine.java

package com.example.myproject.room.manager;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.example.myproject.room.Student;
import com.example.myproject.room.StudentDAO;
import com.example.myproject.room.StudentDatabase;
import java.util.List;

/**
 * DB的引擎
 */
public class DBEngine {

    // 只需要拿到dao,就能够对数据库 增删改查了
    private StudentDAO studentDAO;

    public DBEngine(Context context){
        StudentDatabase studentDatabase = StudentDatabase.getInstance(context);
        studentDAO=studentDatabase.getStudentDao();
    }


    /**
     * dao 增删改查
     * @param students
     */

    // insert 插入
    public void insertStudents(Student ... students){
        new InsertAsyncTask(studentDAO).execute(students);
    }

    //update 更新
    public void updateStudents(Student ... students){
        new UpdateAsyncTask(studentDAO).execute(students);
    }

    // delete 删除 条件
    public void deleteStudents(Student... students) {
        new DeleteAsyncTask(studentDAO).execute(students);
    }

    // delete 全部删除
    public void deleteAllStudents() {
        new DeleteAllAsyncTask(studentDAO).execute();
    }

    // 查询全部
    public void queryAllStudents() {
        new QueryAllAsyncTask(studentDAO).execute();
    }


    /**
     * 如果我们想玩数据库 默认是异步线程  ============  异步操作
     */
    // insert 插入
    static class InsertAsyncTask extends AsyncTask<Student,Void,Void>{

        private StudentDAO dao;

        public InsertAsyncTask(StudentDAO studentDAO){
            dao=studentDAO;
        }

        @Override
        protected Void doInBackground(Student... students) {
            dao.insertStudents(students);
            return null;
        }
    }

    //update 更新
    static class UpdateAsyncTask extends AsyncTask<Student,Void,Void>{

        private StudentDAO dao;

        public UpdateAsyncTask(StudentDAO studentDAO){
            dao=studentDAO;
        }

        @Override
        protected Void doInBackground(Student... students) {
            dao.updateStudents(students);
            return null;
        }
    }

    //delete 删除 条件
    static class DeleteAsyncTask  extends AsyncTask<Student,Void,Void>{

        private StudentDAO dao;

        public DeleteAsyncTask (StudentDAO studentDAO){
            dao=studentDAO;
        }

        @Override
        protected Void doInBackground(Student... students) {
            dao.deleteStudents(students);
            return null;
        }
    }

    //删除 全部删除
    static class  DeleteAllAsyncTask extends AsyncTask<Void,Void,Void>{

        private StudentDAO dao;

        public DeleteAllAsyncTask (StudentDAO studentDAO){
            dao=studentDAO;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            dao.deleteAllStudents();
            return null;
        }
    }

    //全部 查询
    static class QueryAllAsyncTask extends AsyncTask<Void,Void,Void>{

        private StudentDAO dao;

        public QueryAllAsyncTask(StudentDAO studentDao) {
            dao = studentDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            List<Student> allStudent = dao.getAllStudent();
            for (Student student : allStudent) {
                Log.e("dl", "doInBackground: 全部 查询 每一项:" + student.toString() );
            }
            return null;
        }
    }
}

MainActivity4.java

package com.example.myproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.example.myproject.room.Student;
import com.example.myproject.room.manager.DBEngine;

public class MainActivity4 extends AppCompatActivity {

    private DBEngine dbEngine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);

        dbEngine=new DBEngine(this);
    }

    /**
     * 插入
     * @param view
     */
    public void insertAction(View view) {
        Student student1 = new Student("张三", 20);
        Student student2 = new Student("李四", 23);
        Student student3 = new Student("王五", 27);
        dbEngine.insertStudents(student1, student2, student3);

    }

    /**
     * 修改  下标为 3   修改成:"李元霸", 40
     * @param view
     */
    public void updateAction(View view) {
        Student student = new Student("李元霸", 20);
        student.setId(3);
        dbEngine.updateStudents(student);
    }

    /**
     * 删除 条件 下标为 3
     * @param view
     */
    public void deleteAction(View view) {
        Student student=new Student(null,0);
        student.setId(3);
        dbEngine.deleteStudents(student);
    }

    /**
     * 查询
     * @param view
     */
    public void queryAction(View view) {
        dbEngine.queryAllStudents();
    }

    /**
     * 全部删除
     * @param view
     */
    public void deleteAllAction(View view) {
        dbEngine.deleteAllStudents();
    }
}

此时就已完成对room的基础学习

猜你喜欢

转载自blog.csdn.net/weixin_53443677/article/details/126448164