1.添加依赖:
implementation 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
2.创建Entity实体类:
每个Entity实体对象都会映射为表中的某一行
@Entity(tableName = "student") //使用Entity注解定义表名为student
public class Student{
@PrimaryKey(autoGenerate = true) //设置主键,并且定义自增增
@ColumnInfo(name = "uid")
private int uid;
@ColumnInfo(name = "name") //这里变量名和字段名不同,注解不可省略
private String studentName;
private String age; //变量名和字段名都是age,可以省略不写
public User() { //必须指定一个构造方法,room框架需要。并且只能指定一个
}
@Ignore //其他构造方法要添加@Ignore注解
public User(int uid) {
this.uid = uid;
}
public int getUid() { //三个字段的Setter、Getter方法必须添加,这里省略
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
...
}
3.创建Dao接口:
@Dao
public interface StudentDao {
@Query("SELECT * FROM user")
List<Student> getAllStudent();
@Insert
void insert(Student... users);
@Update
void update(Student... users);
@Delete
void delete(Student... users);
}
Insert, Update, Delete可以传入多种不同的参数。例如:
@Insert
void insert(Student... students);
@Insert
void insert(Student student);
@Insert
void insert(List<Student> studentLists);
Query也可以返回多种不同的类型。
@Query("SELECT * FROM student")
List<Student> getAllStudent();
@Query("SELECT * FROM student WHERE id=:id")
User getStudent(int id);
@Query("SELECT * FROM student")
Cursor getStudentCursor();
@Query("SELECT * FROM user WHERE age=:age")
List<User> getStudentByAge(int age);
4.创建数据库:
@Database(entities = { Student.class }, version = 1,exportSchema = false)
public abstract class StudentDatabase extends RoomDatabase {
private static final String DB_NAME = "StudentDatabase.db";
private static volatile StudentDatabase instance;
static synchronized StudentDatabase getInstance(Context context) {
if (instance == null) {
instance = create(context);
}
return instance;
}
private static StudentDatabase create(final Context context) {
return Room.databaseBuilder(
context,
StudentDatabase.class,
DB_NAME).build();
}
public abstract UserDao getUserDao();
}
5.使用数据库:
必须在后台线程中使用数据库,否则会报错
Student student = new Student();
student.setName("Tom");
student.setAge(18);
UserDatabase
.getInstance(context)
.getUserDao()
.insert(student);
List<User> allUsers = UserDatabase
.getInstance(context)
.getUserDao()
.getAllStudents();
6.数据库迁移:
1.在Student实体类中新增一个字段:
private int grade;
2.在Student实体类中新增一个字段:
@Database(entities = { Student.class }, version = 2, exportSchema = false)
public abstract class StudentDatabase extends RoomDatabase {
//...
public abstract UserDao getUserDao();
}
3.创建一个Migration对象,在数据库中新增grade列
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE department ADD COLUMN grade INTEGER");
}
};
4.在数据库对象创建时候添加该Migration对象
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "roomDemo-database")
.addMigrations(AppDatabase.MIGRATION_1_2)
.build();