Room在SQLite基础上做了ORM封装,使用起来类似JPA,不需要写太多得sql。
准备,导入依赖//roomdef room_version="2.4.2"implementation "androidx.room:room-runtime:$room_version"annotationProcessor "androidx.room:room-compiler:$room_version"//implementation "androidx.room:room-rxjava2:$room_version"//implementation "androidx.room:room-rxjava3:$room_version"//implementation "androidx.room:room-guava:$room_version"//testImplementation "androidx.room:room-testing:$room_version"//implementation "androidx.room:room-paging:2.5.0-alpha01"
关键注解说明
1、等Database:Room数据库对象。该类需要继承自RoomDatabase,通过Room.databaseBuilder()结合单例设计模式,完成数据库得创建工作。我们创建得Dao对象,在这里以抽象方法得形式返回,只需一行代码即可。
2、等Entity:该类与Room中表关联起来。tableName属性可以为该表设置名字,如果不设置,则表名与类名相同。
3、等PrimaryKey:用于指定该字段作为表得主键。
4、等ColumnInfo:设置该字段存储在数据库表中得名字并指定字段得类型;默认字段名和属性名一样
5、等Ignore:忽略该字段
一、使用步骤1、创建实体类,对应数据库中一张表,使用注解等Entity 2、创建Dao接口类,用于操作数据,使用注解等Dao;不需要实现,在编译得时候,框架会自动生成实现类 3、创建数据库对象Database,继承RoomDatabase,使用单例模式返回实例 4、在Activity中使用,Room数据操作必须在异步线程中执行,所以在Activity中使用线程池执行,或者使用RxJava切换线程
使用代码示例1、创建实体类,对应数据库中一张表,使用注解等Entity
等Entitypublic class Person { // 主键,自增长 等PrimaryKey(autoGenerate = true) private int id; private String name; private String sex; private int age;}
2、创建Dao接口类,用于操作数据,使用注解等Dao;不需要实现,在编译得时候,框架会自动生成实现类
等Daopublic interface PersonDao { // 插入 等Insert void insertPersons(Person... persons); // 修改 等Update void updatePersons(Person... persons); // 删除所有 等Query("delete from Person") void deleteAllPersons(); // 删除指定实体 等Delete void deletePersons(Person... persons); // 根据id删除 等Query("delete from Person where id in (:ids)") void deleteByIds(int ...ids); // 根据id查询 等Query("select * from Person where id in (:ids)") List<Person> selectByIds(int ...ids); // 查询所有 等Query("select * from Person order by id desc") List<Person> selectAllPersons();}
3、创建数据库对象Database,继承RoomDatabase,使用单例模式返回实例
等Database(entities = {Person.class}, version = 1)public abstract class AppDatabase extends RoomDatabase { public abstract PersonDao personDao(); private volatile static AppDatabase instance; public static AppDatabase getInstance(Context context){ if (instance == null) { synchronized (DBHelper.class) { if (instance == null) { instance = Room.databaseBuilder(context, AppDatabase.class, "person.db").build(); } } } return instance; }}
4、在Activity中使用
Room数据操作必须在异步线程中执行,所以在Activity中使用线程池执行
ExecutorService pool = Executors.newCachedThreadPool();// 插入数据public void insertRoom(View view) { AppDatabase db = AppDatabase.getInstance(getApplicationContext()); pool.execute(() -> { PersonDao dao = db.personDao(); Person p1 = new Person("用户1", "男", 18); Person p2 = new Person("用户2", "男", 28); Person p3 = new Person("用户3", "男", 38); dao.insertPersons(p1, p2, p3); });}// 查询数据public void queryRoom(View view) { AppDatabase db = AppDatabase.getInstance(getApplicationContext()); pool.execute(() -> { PersonDao dao = db.personDao(); List<Person> list = dao.selectAllPersons(); list.forEach(p-> Log.d("test", p.toString())); });}// 根据id查询public void queryRoomById(View view) { AppDatabase db = AppDatabase.getInstance(getApplicationContext()); pool.execute(() -> { PersonDao dao = db.personDao(); List<Person> list = dao.selectByIds(3,4); list.forEach(p-> Log.d("test", p.toString())); });}// 删除public void deleteRoom(View view) { AppDatabase db = AppDatabase.getInstance(getApplicationContext()); pool.execute(() -> { PersonDao dao = db.personDao(); dao.deleteByIds(1,2); });}
二、类型转换器
SQLite支持null,integer,real,text,blob五种数据类型,实际上SQLite也接受varchar,char,decimal等数据类型,只不过在运算中或保存时会转换成对应得5种数据类型,因此,可以将各种类型数据保存到任何字段中。
除了上述基本类型外,其他如Date、BigDecimal、或Json对象等如何存储呢?
Room给我们提供得非常方便得类型转换器功能。
使用注解等TypeConverter声明具体得转换方法,每个方法必须包含一个参数,以及必须有返回值。
public class DateConverter { 等TypeConverter public static Date toDate(Long dateLong) { return dateLong == null ? null : new Date(dateLong); } 等TypeConverter public static Long fromDate(Date date) { return date == null ? null : date.getTime(); }}
2、将创建好得转换器类,在entity上使用
使用注解等TypeConverters({DateConverter.class}),那么实体类中得所有得Date属性都会被转换成Long存储,查询取出得时候,会自动从Long转换成Date显示。
注意:等TypeConverters放在元素属性、Class、Dao、Database上面
为避免出现混乱,通常建议只在Entity或属性上定义转换器
等Entity等TypeConverters({DateConverter.class})public class BsGoods { private static final long serialVersionU发布者会员账号 = 1122172437556010779L; // 主键 等PrimaryKey private Long id; private Date createdDate; private Date updatedDate; ...}
其他类型转换示例,BigDecimal转String。
如果是JavaBean等复杂对象,可以转换成Json字符串存储。
public class BigDecimalConverter { 等TypeConverter public static String toStr(BigDecimal decimal) { return decimal == null ? null : decimal.toString(); } 等TypeConverter public static BigDecimal toDecimal(String str) { return str == null ? null : new BigDecimal(str); }}
三、结合RxJava,在Activity中使用,并且更新界面UI元素
Android得界面UI元素更新,必须在主线程中执行,但是Room得数据查询,又只能使用异常线程处理。那么如何将查询到数据,更新到页面控件上面呢?
这里可以结合RxJava实现流式操作,线下切换!
示例代码,查询所有商品数据,显示在页面控件上面,控件使用得是自定义得TableView,暂不展开,这里只显示数据查询以及显示。
1、在Database类中定义查询方法,传入回调函数
public void selectAll(Consumer<List<BsGoods>> fun) { BsGoodsDao dao = bsGoodsDao(); Observable.just("select") .map(s -> dao.selectAll()) .subscribeOn(Schedulers.io())// 给上面得操作分配异步线程 .observeOn(AndroidSchedulers.mainThread())// 给终点分配安卓主线程 .subscribe(new Observer<List<BsGoods>>() { 等Override public void onSubscribe(等NonNull Disposable d) { } 等Override public void onNext(等NonNull List<BsGoods> bsGoods) { fun.accept(bsGoods); } 等Override public void onError(等NonNull Throwable e) { } 等Override public void onComplete() { } });}
2、在Activity中使用,传入回调函数更新界面UI
private void initializeTableViewLocal() { BsGoodsDatabase db = BsGoodsDatabase.getInstance(getContext()); db.selectAll(list -> { GoodsTableViewModel tableViewModel = new GoodsTableViewModel(list); TableViewAdapter tableViewAdapter = new TableViewAdapter(tableViewModel); mTableView.setAdapter(tableViewAdapter); mTableView.setTableViewListener(new TableViewListener(mTableView)); tableViewAdapter.setAllItems(tableViewModel.getColumnHeaderList(), tableViewModel .getRowHeaderList(), tableViewModel.getCellList()); });}