1允许使用androidx
gradle.properties
android.useAndroidX=true
android.enableJetifier= true
2build.gradle 引入room依赖
// Room的支持
def room_version = "2.2.0-alpha01"
implementation "androidx.room:room-runtime:$room_version" // Room 的 APi支持
annotationProcessor "androidx.room:room-compiler:$room_version" // Room 的注解处理器
3 创建student表@Entity
package com.hisense.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 +
'}';
}
}
4创建接口dao,对数据库进行增删改查
@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();
}
5 创建数据库,关联dao
package com.hisense.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 {
// 用户只需要操作dao,我们必须暴露dao,dao被用户拿到后,就能对数据库 增删改查了
public abstract StudentDao getStudentDao();
// 单例模式 返回 DB
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;
}
}
6创建数据库引擎,使用异步任务在子线程中操作数据库(耗时)
package com.hisense.room.manager;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.hisense.room.Student;
import com.hisense.room.StudentDao;
import com.hisense.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);
}
}
// 删除 全部删除
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;
}
}
}
7 activity中实际调用
package com.hisense.room;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import com.hisense.room.manager.DBEngine;
import com.hisense.test.R;
public class RoomActivity extends AppCompatActivity {
private DBEngine dbEngine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
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();
}
}
layout
<?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"
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>