以录入书籍信息为例,使用Room框架的编码过程分为下列五步:
1、编写书籍信息表对应的实体类,该类添加“@Entity”注解
package com.example.study_android.entity;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class BookInfo {
@PrimaryKey(autoGenerate = true)
private int id;
public String name;
public String author;
public double price;
@Override
public String toString() {
return "BookInfo{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
2、编写书籍信息表对应的持久化类,该类添加“@Dao”注解
@Dao
public interface BookDao {
@Insert
void insert(BookInfo... book);
@Delete
void delete(BookInfo... book);
@Query("DELETE FROM BookInfo")
void deleteAll();
@Update
int update(BookInfo... book);
@Query("SELECT * FROM BookInfo")
List<BookInfo> queryAll();
@Query("SELECT * FROM BookInfo WHERE name=:name ORDER BY id DESC limit 1")
BookInfo queryByName(String name);
}
3、编写书籍信息表对应的数据库类,该类从RoomDatabase派生而来,并添加“@Database”注解
package com.example.study_android.database;
import androidx.room.Database;
import androidx.room.RoomDatabase;
import com.example.study_android.dao.BookDao;
import com.example.study_android.entity.BookInfo;
@Database(entities = {BookInfo.class}, version = 1, exportSchema = true)
public abstract class BookDatabase extends RoomDatabase {
// 获取该数据库中某张表的持久化对象
public abstract BookDao bookDao();
}
- entities:表示该数据库有哪些表
- exportSchema:表示是否导出数据库信息的json串,建议设为false,若设为true还需指定json文件的保存路径
在build.gradle中添加导出路径
javaCompileOptions {
annotationProcessorOptions {
//指定数据库schema导出的位置
arguments += mapOf(
"room.schemaLocation" to "$projectDir/schemas",
"room.incremental" to "true"
)
}
}
4、在自定义的Application类中声明书籍数据库的唯一实例
public class MyApplication extends Application {
private static MyApplication mApp;
// 声明一个书籍数据库对象
private BookDatabase bookDatabase;
public static MyApplication getInstance() {
return mApp;
}
// App启动时调用
@Override
public void onCreate() {
super.onCreate();
mApp = this;
// 构建书籍数据库的实例
bookDatabase = Room.databaseBuilder(this, BookDatabase.class, "'book")
// 允许迁移数据库(发生数据库变更时,Room默认删除原数据库再创建新数据库,如此一来原来的记录会丢失,故而要改为迁移方式以便保存原有记录)
.addMigrations()
// 允许主线程中操作数据库(Room默认不能在主线程中操作数据库)
.allowMainThreadQueries()
.build();
}
public BookDatabase getBookDB() {
return bookDatabase;
}
}
5、在操作书籍信息表的地方获取数据表的持久化对象
bookDao = MyApplication.getInstance().getBookDB().bookDao();
@Override
public void onClick(View view) {
String name = et_book_name.getText().toString();
String author = et_author.getText().toString();
String price = et_price.getText().toString();
switch (view.getId()) {
case R.id.btn_save:
BookInfo book = new BookInfo();
book.name = name;
book.author = author;
book.price = Double.parseDouble(price);
bookDao.insert(book);
ToastUtil.show(this, "保存成功");
break;
case R.id.btn_del:
BookInfo b2 = new BookInfo();
b2.id = 1;
bookDao.delete(b2);
break;
case R.id.btn_edit:
BookInfo b3 = new BookInfo();
BookInfo b4=bookDao.queryByName(name);
b3.id = b4.id;
b3.name = name;
bookDao.update(b3);
break;
case R.id.btn_query:
List<BookInfo> list = bookDao.queryAll();
StringBuilder sb = new StringBuilder();
for (BookInfo b : list) {
sb.append(b.toString());
}
tv_result.setText(sb);
break;
}
}
案例代码