此文,为room的第一篇随笔,记录room的基础使用方式。后续还会记录一些补充的内容。
app.gradle导入库:
dependencies { // 当前 targetSdk 32 // API 33 可以使用2.5.0 def room_version = "2.4.3" implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" }
构建表单对象:
@Entity(tableName = "teacher_table") public class Teacher { @PrimaryKey(autoGenerate = true) public int id; @ColumnInfo(name = "name") public String name; @ColumnInfo(name = "age") public String age; public static Teacher[] getTeachers() { Teacher[] teachers = new Teacher[1000]; for (int i = 0; i < teachers.length; i++) { Teacher teacher = new Teacher(); teacher.name = "老师" + i; teacher.age = "岁:" + i; teachers[i] = teacher; } return teachers; } }
构建Dao对象(读、写数据库的类):
@Dao public interface TeacherDao { // 向表中,插入数据 @Insert void insetTeachers(Teacher... teachers); // 删除所有数据 @Query("delete from teacher_table") void deleteAllTeachers(); // 查看所有数据 @Query("select * from teacher_table order by id") DataSource.Factory<Integer, Teacher> getAllTeachers(); }
构建数据库对象:
@Database( entities = {Teacher.class}, version = 1, exportSchema = false ) public abstract class AppDatabase extends RoomDatabase { private static final String DB_NAME = "swalkaDb"; private static volatile AppDatabase instance = null; public static AppDatabase getInstance(Context appContext) { if (null == instance) { synchronized (AppDatabase.class) { if (null == instance) { instance = Room.databaseBuilder( appContext, AppDatabase.class, DB_NAME ) // 允许在主线程创建数据库。一般不建议在主线程构建数据库 .allowMainThreadQueries() .build(); } } } return instance; } public abstract TeacherDao teacherDao(); }
Activity中使用:
// 构建/打开 数据库。建议在子线程中使用 AppDatabase appDatabase = AppDatabase.getInstance(getApplicationContext()); // 获取到操作类 TeacherDao dao = appDatabase.teacherDao(); // TODO 开始数据库操作,在子线程操作数据库
备注:
1、代码由Java实现,如果是 kotlin,在 gradle 导入时,需要先导入 kapt 插件(可在往期随笔中查看如何导入 kapt 插件),同时修改 annotationProcessor 为 kapt
2、此笔记为单表结构,后续会发出关联表结构
标签:room,AppDatabase,jetpack,数据库,Teacher,public,android,teacher From: https://www.cnblogs.com/swalka/p/17059044.html