First, use
1, Build.gradle introduced
compile "android.arch.persistence.room:runtime:1.0.0"annotationProcessor ‘android.arch.persistence.room:compiler:1.0.0‘
If the second line is less introduced, the error will be:
Caused by: java.lang.RuntimeException: cannot find implementation for com.hy.room.HyDatabase. HyDatabase_Impl does not exist
2. Create a new entity class
@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
3. Establishing the DAO class interface
@Daopublic interface UserDao { @Insert public long[] insertUsers(User... users); @Insert public void insertUserList(List<User> users); @Update public void updateUsers(User... users); @Delete public void deleteUsers(User... users); @Query("select * from User") public List<User> searchAllUsers(); @Query("select * from User where :age > 18") public List<User> searchUsersByAge(int age); @Query("select firstName,age from user") public List<SimpleUser> searchAllSimpleUsers(); @Query("select * from User where firstName like :name limit 1") public User searchUserByName(String name);}
4, establish the Inheritance Roomdatabase database management virtual class
@Database(entities = {User.class}, version = 1) public abstract class HyDatabase extends RoomDatabase { public abstract UserDao userDao();
5. Initialize the database
HyDatabase database = Room.databaseBuilder(this, HyDatabase.class, "room.db").build();
6. Operation example (use with Rxjava)
Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(ObservableEmitter<String> e) throws Exception { List<User> users = database.userDao().searchAllUsers(); e.onNext(new Gson().toJson(users)); } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<String>() { @Override public void accept(String s) throws Exception { textView.setText(s); } });
All users are queried in the sub-thread (the main thread operations database will error), converted to a JSON-formatted string by Gson, and then displayed in the main thread.
second, the database upgrade
1, new to increase the entity class.
2, in the database entities annotations Add the new entity class, and the version number plus one.
3. Add the Addmigrations () method where the database is initialized, and implement the migration class, for example:
HyDatabase database = Room.databaseBuilder(this, HyDatabase.class, "room.db") .addMigrations(migration) .build();
And
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`))"); }
Represents an upgrade from version 1 to version 2, manually adding SQL to the new table.
Iii. Summary
Advantages:
1, from the above example can be seen, the operation is very simple, do not need to like before, from the Sqllite query data, and then a property assembly into the entity class.
2, the increase and deletion of the operation is very simple, only need a note to be done.
Disadvantages:
1, can not use the Android Debug database online view?
2. Can not configure fuzzy query conditions?
3. The database upgrade cannot be automated and does not provide a friendly API, it also requires handwritten SQL statements, and must ensure that the handwritten SQL statement is identical to the annotations in the created entity class, otherwise it will be an error, for example:
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=[]}
Iv. The Pit of God
1. Error
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 says it is not possible to find the _impl implementation class, which appears to be a compilation problem. Look at the configuration and code, found that there are no problems, after a few hours of trying to finally find the problem of configuration, the problem is in this line:
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
All of our third-party introductions are in third this module, and then in other module write business code, the above line of code is only configured on the thrid above, resulting in the implementation of the module does not run the compiled room code, so naturally did not generate the implementation class. You should also add the above line of code to the module that uses the.
Reference:
Official documents (FQ required)
Google's official Android App Architecture Library--room Persistence Library
Android Hostel Frame Learning notes