首页 > 其他分享 > 46. Room

46. Room

时间:2022-09-20 08:11:48浏览次数:35  
标签:room 46 void Student import android public Room

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'

同步

编写三角色

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;
    }
}


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();
}

 


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;
    }

 

}

 


46.3 Room实战
用户只需要拿DAO

布局

<?xml version="1.0" encoding="utf-8"?>
<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>

 


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 +
                '}';
    }
}

 


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;
    }

 

}

 


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();
}

 


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;
        }
    }

}

 


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();
    }
}

运行

在这里插入图片描述

 

标签:room,46,void,Student,import,android,public,Room
From: https://www.cnblogs.com/55zjc/p/16709772.html

相关文章

  • Room数据库(以book类为例)
    使用Room实体定义数据|Android开发者|AndroidDevelopers(google.cn)在build.gradle中加入以下引用//roomdefroom_version="2.4.3"implementation"andro......
  • AcWing 4604. 集合询问
    https://www.acwing.com/problem/content/4607/哈希表题意:初始时空集{},进行t次操作,操作分为:+x,将一个非负整数x添加至集合中。注意,集合中可以存在多个相同的整......
  • Ubuntu Jenkins升级2.346.3后远程调用403解决方案(HTTP ERROR 403 No valid crumb was
       一般通过api调用Jenkinsjob出现403(HTTPERROR403Novalidcrumbwasincludedintherequest)报错,是因为新版本Jenkins为了安全,搞的一套crsf认证机制,具体的自......
  • 题解【P2466 [SDOI2008] Sue 的小球】
    题目传送门。一眼丁真,鉴定为原题。现将所有点按照\(x\)排序,区间\([l,r]\)的终点一定是\(l\)或\(r\),否则会跑冤枉路。设\(f_{i,j,0/1}\)表示在区间\([i,j]\)......
  • Meeting Rooms III
    MeetingRoomsIIIYouaregivenaninteger$n$.Thereare$n$roomsnumberedfrom$0$to$n-1$.Youaregivena2Dintegerarray meetings where meetings[i......
  • 46 | JAVA_IO_使用Files
    使用Files虽然Files是java.nio包里面的类,但他俩封装了很多读写文件的简单方法,例如,我们要把一个文件的全部内容读取为一个byte[],可以这么写:byte[]data=Files.readAllBy......
  • LeetCode 46 全排列
    classSolution{public:vector<vector<int>>res;vector<int>path;boolused[10];voiddfs(vector<int>&nums){if(path.size()==nu......
  • CF446C(线段树+斐波那契)
    CF446C(线段树+斐波那契数列)CF链接洛谷链接题目大意:区间加斐波那契数列,区间求和分析:一眼鉴定为线段树难点在于如何打标记,合并和传递标记对于斐波那契数列有几个性......
  • [LC646]最长数对链
    题目概述给出 n 个数对。 在每一个数对中,第一个数字总是比第二个数字小。现在,我们定义一种跟随关系,当且仅当 b<c 时,数对(c,d) 才可以跟在 (a,b) 后面。我们......
  • ARC146 部分题解
    A普及组题//byBalloons#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#definemprmake_pair#definedebug()cerr<<"Madoka"<<e......