Room
Room使用
表的定义
@Entity
- @PrimaryKey
- 主键
- autoGenerate=true 自增长
- @ColumnInfo
- 字段
- name=”jett” 字段名
- @Ignore
- 表示一个属性不加入生成表的字段,只是临时使用
数据访问对象的定义
@Dao
List getAll();
- 可以把参数加入查询语句
- //查询一条记录
@Query(“select * from Student where name like:name”)
Student findByName(String name);
//查找部份ID号的记录
@Query(“select * from Student where uid in (:userIds)”)
List getAllId(int[] userIds);
- @Insert
- 插入
- @Insert
void insert(Student… students);
- @Insert
- 插入
- @Delete
- 删除
- @Delete
void delete(Student student);
- @Delete
- 删除
- @Update
- 更新
- @Update
void update(Student student);
- @Update
- 更新
数据库的定义
@Database
- entities={Student.class}
- 定义数据库中包含的表
- version=1
- 数据库版本号
- @Database(entities = {Student.class},version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract StudentDao userDao();
}
返回例的子集
public class NameTuple {
1 | @ColumnInfo(name="first_name") |
}
@Dao
public interface MyDao {
@Query(“SELECT first_name, last_name FROM user”)
public List loadFullName();
}
表与表之间的实体联系
@Entity(foreignKeys = @ForeignKey(entity = User.class,
1 | parentColumns = "id", |
public class Book {
@PrimaryKey
public int bookId;
1 | public String title; |
}
创建嵌套对象
public class Address {
1 | public String street; |
}
@Entity
public class User {
@PrimaryKey
public int id;
1 | public String firstName; |
}
传递参数集合
@Dao
public interface MyDao {
@Query(“SELECT first_name, last_name FROM user WHERE region IN (:regions)”)
public List loadUsersFromRegions(List regions);
}
可观察的查询
@Dao
public interface MyDao {
@Query(“SELECT first_name, last_name FROM user WHERE region IN (:regions)”)
public LiveData loadUsersFromRegionsSync(List regions);
}
@Dao
public interface MyDao {
@Query(“SELECT user.name AS userName, pet.name AS petName “
- “FROM user, pet “
- “WHERE user.id = pet.user_id”)
public LiveData- loadUserAndPetNames();
// You can also define this class in a separate file, as long as you add the
// “public” access modifier.
static class UserPet {
public String userName;
public String petName;
}
}
支持Rxjava
@Dao
public interface MyDao {
@Query(“SELECT * from user where id = :id LIMIT 1”)
public Flowable loadUserById(int id);
}
返回Cursor
@Dao
public interface MyDao {
@Query(“SELECT * FROM user WHERE age > :minAge LIMIT 5”)
public Cursor loadRawUsersOlderThan(int minAge);
}
Room数据库迁移
Room.databaseBuilder(getApplicationContext(), MyDb.class, “database-name”)
1 | .addMigrations(MIGRATION_1_2, MIGRATION_2_3).build(); |
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL(“CREATE TABLE Fruit
(id
INTEGER, “
- “
name
TEXT, PRIMARY KEY(id
))”);
}
};
static final Migration MIGRATION_2_3 = new Migration(2, 3) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL(“ALTER TABLE Book “
- “ ADD COLUMN pub_year INTEGER”);
}
};
XMind - Trial Version