• Android学习笔记 46. Room


    Android学习笔记

    Android基础开发——数据存储

    46. Room

    46.1 Room三角色介绍

    → → Room 是SQLite数据库的抽象

    流畅易用的访问数据库。

    • Entity :Student
    • DAO :DAO
    • DB:StudentDatabase

    注解

    46.2 Room三角色编写

    引入依赖

    implementation 'androidx.room:room-runtime:2.4.3'
    annotationProcessor 'androidx.room:room-compiler:2.4.3'
    
    • 1
    • 2

    在这里插入图片描述

    同步

    编写三角色

    Student.java

    package com.dingjiaxiong.room;
    
    
    import androidx.room.Entity;
    import androidx.room.PrimaryKey;
    
    @Entity
    public class Student {
    
        @PrimaryKey(autoGenerate = true)
        private int id;
    
        private String name;
    
        private int age;
    
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    
        public Student(int id, 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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    StudentDAO.java

    package com.dingjiaxiong.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;
    
    @Dao
    public interface StudentDAO {
    
        //增
        @Insert
        void insertStudents(Student ... students);
    
        //改
        @Update
        void updateStudents(Student ... students);
    
        //删
        @Query("DELETE FROM Student")
        void deleteAllStudents();
    
        //查
        @Query("SELECT * FROM Student ORDER BY ID DESC")
        List<Student> getAllStudent();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    StudentDatabase.java

    package com.dingjiaxiong.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 {
    
    
        public abstract StudentDAO getStudentDao();
    
        private static StudentDatabase INSTANCE;
        public static synchronized StudentDatabase getInstance(Context context){
            if(INSTANCE == null){
                INSTANCE = Room.databaseBuilder(
                        context.getApplicationContext(),StudentDatabase.class,"student_database")
                        //默认异步线程
                        // .allowMainThreadQueries()
                        .build();
            }
    
            return INSTANCE;
        }
    
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    46.3 Room实战

    用户只需要拿DAO

    布局

    
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity2"
        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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    Student.java

    package com.dingjiaxiong.room;
    
    
    import androidx.room.Entity;
    import androidx.room.PrimaryKey;
    
    // 一张表(主键唯一 主键自动增长, name,age)
    @Entity
    public class Student {
    
        // 主键唯一  主键自动增长
        @PrimaryKey(autoGenerate = true)
        private int id;
    
        private String name;
    
        private int age;
    
        /*public Student() {
        }*/
    
        public Student(String name, int age) {
            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;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59

    StudentDatabase.java

    package com.dingjiaxiong.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 {
    
    
        public abstract StudentDao getStudentDao();
    
        private static StudentDatabase INSTANCE;
        public static synchronized StudentDatabase getInstance(Context context){
            if(INSTANCE == null){
                INSTANCE = Room.databaseBuilder(
                        context.getApplicationContext(),StudentDatabase.class,"student_database")
                        //默认异步线程
                        .allowMainThreadQueries()
                        .build();
            }
    
            return INSTANCE;
        }
    
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    StudentDao.java

    package com.dingjiaxiong.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;
    
    @Dao // Database access object == 对表进行 增删改查
    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();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    DBEngine.java

    package com.dingjiaxiong.room.manager;
    
    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;
    
    import com.dingjiaxiong.room.Student;
    import com.dingjiaxiong.room.StudentDao;
    import com.dingjiaxiong.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 增删改查
    
        // 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) { // 既然传递了 student 进来,就是条件删除
                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;
            }
        }
    
        // 全部 查询
        private 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("Derry", "doInBackground: 全部 查询 每一项:" + student.toString() );
                }
    
                return null;
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140

    MainActivity2.java

    package com.dingjiaxiong.mysqlite;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.view.View;
    
    import com.dingjiaxiong.room.Student;
    import com.dingjiaxiong.room.manager.DBEngine;
    
    
    // Room 的学习
    public class MainActivity2 extends AppCompatActivity {
    
        private DBEngine dbEngine;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
    
            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("李元霸", 40);
            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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    运行

    在这里插入图片描述

  • 相关阅读:
    web前端要接触的技术领域与关键要素
    Hadoop HA高可用集群模式搭建指南
    2023 年 的 DBA 有哪些变化?
    msvcp120.dll丢失的解决方法,有效的两种msvcp120.dll修复方法分享
    《向量数据库指南》——Range Search 使用方法和参数检查
    含免费次数的API接口资源分享
    java计算机毕业设计评标专家管理信息系统源码+数据库+系统+lw文档+mybatis+运行部署
    【杂七杂八】Huawei Gt runner手表系统降级
    git修改远程仓库地址
    CVPR 2022 | UniDet:通用的多数据集目标检测
  • 原文地址:https://blog.csdn.net/weixin_44226181/article/details/126314420