- 在
build.gradle
中引入依赖
dependencies {
...
implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
...
}
- 创建实体类
@Entity(tableName = "user")
public class User {
@PrimaryKey
private int uid;
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;
public User() {
}
@Ignore
public User(int uid, String firstName, String lastName) {
this.uid = uid;
this.firstName = firstName;
this.lastName = lastName;
}
// 此处省略了Getter/Settter方法...
}
- 创建Dao接口类,这里只演示了最基本的增删改查,这个接口不需要写实现类,它的实现类会由
android
根据方法上的注解自动生成
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Insert
void insertAll(User...users);
@Delete
void delete(User user);
@Update
void update(User user);
@Query("DELETE FROM user")
void deleteAll();
}
- 创建继承自
RoomDatabase
的抽象类,这个类时访问数据库的关键。在这个抽象类中用注解配置与数据库中的表相关联的实体类,并提供返回Dao
对象的抽象方法。
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
- 在
build.gradle
中配置数据库的Schema的导出路径, 如下配置的导出路径为app/schemas/
android {
...
defaultConfig {
...
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
...
}
...
}
如果不需要导出Schema,可以再第四步中使用如下配置
@Database(entities = {User.class}, version = 1, exportSchema = false)
- 因为是在界面中使用一个按钮触发测试代码,所以写在了
onClick
方法中
public class MainActivity extends AppCompatActivity {
...
public void onClick(View view) {
// 获得 AppDatabase 的对象,传入的第三个参数为数据库中表的名字
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "user").build();
final UserDao userDao = db.userDao();
// 访问数据库的操作要在子线程中执行
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
userDao.deleteAll();
System.out.println("----------- INSERT U1 U2 -------------");
User u1 = new User(1, "a", "b");
User u2 = new User(2, "c", "d");
userDao.insertAll(u1, u2);
List<User> users = userDao.getAll();
System.out.println(users.toString());
System.out.println("------------- DELETE U2 --------------");
userDao.delete(u2);
users = userDao.getAll();
System.out.println(users.toString());
u1.setFirstName("aa");
u1.setLastName("bb");
System.out.println("------------- UPDATE U1 --------------");
userDao.update(u1);
users = userDao.getAll();
System.out.println(users.toString());
}
});
thread.start();
}
...
}
- 测试结果
I/System.out: ----------- INSERT U1 U2 -------------
I/System.out: [User{uid=1, firstName='a', lastName='b'}, User{uid=2, firstName='c', lastName='d'}]
I/System.out: ------------- DELETE U2 --------------
I/System.out: [User{uid=1, firstName='a', lastName='b'}]
I/System.out: ------------- UPDATE U1 --------------
I/System.out: [User{uid=1, firstName='aa', lastName='bb'}]
网友评论