Android Room框架学习笔记

时间:2023-12-18 09:50:02

一、使用

1、build.gradle引入

```
compile "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
```

如果少了第二行引入,会报错:

``` Caused by: java.lang.RuntimeException: cannot find implementation for com.hy.room.HyDatabase. HyDatabase_Impl does not exist ```

2、新建一个实体类

```
@Entity(indices = {@Index(value = "firstName", unique = true)})
public class User {

@PrimaryKey(autoGenerate = true)
public int id; public String firstName;
public String lastName;
public int age; @Ignore
private Bitmap bitmap; @Embedded
public Address address;

}

3、建立Dao类接口
<p></p>

@Dao

public interface UserDao {

@Insert
public long[] insertUsers(User... users); @Insert
public void insertUserList(List&lt;User&gt; users); @Update
public void updateUsers(User... users); @Delete
public void deleteUsers(User... users); @Query("select * from User")
public List&lt;User&gt; searchAllUsers(); @Query("select * from User where :age &gt; 18")
public List&lt;User&gt; searchUsersByAge(int age); @Query("select firstName,age from user")
public List&lt;SimpleUser&gt; searchAllSimpleUsers(); @Query("select * from User where firstName like :name limit 1")
public User searchUserByName(String name);

}

4、建立继承RoomDatabase的数据库管理虚类
<p></p>
@Database(entities = {User.class}, version = 1)
public abstract class HyDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
5、初始化数据库
<p></p>
HyDatabase database = Room.databaseBuilder(this, HyDatabase.class, "room.db").build();
6、操作举例(与RxJava配合使用)
<p></p>
Observable.create(new ObservableOnSubscribe&lt;String&gt;() {
@Override
public void subscribe(ObservableEmitter&lt;String&gt; e) throws Exception {
List&lt;User&gt; users = database.userDao().searchAllUsers();
e.onNext(new Gson().toJson(users));
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer&lt;String&gt;() {
@Override
public void accept(String s) throws Exception {
textView.setText(s);
}
});
<p>子线程中查询出所有的用户(主线程操作数据库会报错),用Gson转换成json格式的字符串,主线程中再显示出来。</p>
<p><br /></p>
<p></p>
<h3><strong>二、数据库升级</strong></h3>
1、新建要增加实体类。
<p></p>
<p>2、在database中entities注解加入新增的实体类,同时版本号加一。</p>
<p>3、初始化数据库的地方增加addMigrations()方法,实现Migration类,例如:</p>
<p></p>
HyDatabase database = Room.databaseBuilder(this, HyDatabase.class, "room.db")
.addMigrations(migration)
.build();

<p></p>
private Migration migration = new Migration(1,2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE `Book` (`id` INTEGER, "
+ "`name` TEXT, `owner` INTEGER, PRIMARY KEY(`id`))");
}
};
表示从版本1升级到版本2,手动增加新增的表的sql。<br /><br /><h3><strong>三、总结</strong></h3>
<p>优点:</p>
<p>1、从上面例子可以看出,操作很简单,不需要像以前一样,从SqlLite查询出数据,再一个个属性装配到实体类中。</p>
<p>2、增删改查操作十分简便,只需要一个注解就搞定。<br /></p>
<p>缺点:</p>
<p>1、不能用Android Debug Database在线查看数据库?</p>
<p>2、不能配置模糊查询条件?</p>
<p>3、数据库升级无法自动且未提供友好API,同样需要手写SQL语句,同时必须保证手写的SQL语句与创建的实体类中的注解完全一致,不然会报错,例如:</p>
<p></p>

java.lang.IllegalStateException: Migration didn't properly handle Book(com.hy.room.Book).

Expected:TableInfo{name='Book', columns={name=Column{name='name', type='TEXT', notNull=false, primaryKeyPosition=0}, owner=Column{name='owner', type='INTEGER', notNull=true, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', notNull=true, primaryKeyPosition=1}}, foreignKeys=[], indices=[]}

Found:

TableInfo{name='Book', columns={name=Column{name='name', type='TEXT', notNull=false, primaryKeyPosition=0}, owner=Column{name='owner', type='INTEGER', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', notNull=false, primaryKeyPosition=1}}, foreignKeys=[], indices=[]}

<p><br /></p>
<h3>四、神坑</h3>
<p>1、报错</p>
<p></p>

java.lang.RuntimeException: cannot find implementation for com.hiten.base.db.DbHoc. DbHoc_Impl does not exist

at android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:92)

at android.arch.persistence.room.RoomDatabase$Builder.build(RoomDatabase.java:454)

at com.hiten.base.manager.ManagerDb.init(ManagerDb.java:21)

at com.hiten.base.ApplicationHoc.onCreate(ApplicationHoc.java:52)

log说找不到_impl实现类,看来是编译的问题。查看配置和代码,发现都没有问题,经过几个小时的尝试,终于发现还是配置的问题,问题出在这行:
<p></p>
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
我们所有的第三方引入都在third这个module里面,然后在其他module写业务代码,上面那行代码只配置在thrid上面,导致执行的module没有运行编译room的代码,所以自然没有生成实现类。在使用room的module也要加上上面那行代码。
<p><br /></p>
<h3>参考:</h3>
<p><a href="https://developer.android.com/training/data-storage/room/index.html">官方文档(需*)</a><br /></p>
<p><a href="http://blog.csdn.net/hubinqiang/article/details/73012353">谷歌官方Android应用架构库——Room 持久化库</a><br /></p>
</div>
</div>
</article>