room简介:
在JetPack系列中,Room是一个非常重要的组件。作为一个ORM库,其在原生的SQLite数据库上面进行了封装,以便更好的提供服务
Room的三个注解:
- @Entity:@Entity用来注解实体类,其代表的是一张数据库表,通常情况下@Entity注解中我们传入了一个参数 tableName用来指定表的名称,如果不传默认类名为表名。
(1)@PrimaryKey注解用来标注表的主键,并且使用autoGenerate = true 来指定了主键自增长。
(2)@ColumnInfo注解用来标注表对应的列的信息比如表名、默认值等等。
(3)@Ignore 注解顾名思义就是忽略这个字段,使用了这个注解的字段将不会在数据库中生成对应的列信息。也可以使用@Entity注解中的 ignoredColumns 参数来指定,效果是一样的。
- @Dao:@Dao用来注解一个接口或者抽象方法,该类的作用是提供访问数据库的方法。即通过
@Query、@Insert、@Delete、@Update
来执行数据库的增删改查操作。 - @Database:@Database用来注解类,并且注解的类必须是继承自RoomDatabase的抽象类。该类主要作用是创建数据库和创建Daos(data access objects,数据访问对象)。
Room的使用:
1.首先引入依赖:
dependencies {
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
// optional - RxJava support for Room
implementation "androidx.room:room-rxjava2:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"
}
2.使用Entity注解创建实体类——创建一个表
@Entity(tableName = "users")
class User {
@PrimaryKey
public int id;
@ColumnInfo(name = "first_name")
public String firstName;
@ColumnInfo(name = "last_name")
public String lastName;
@Ignore
Bitmap picture;
}
3.使用Dao注解创建方法调用类
@Dao
public interface UserDao {
@Query("SELECT * FROM "+ UserModel.USER_TABLE_NAME + " WHERE "+
UserModel.NAME + " = :name")
LiveData<UserModel> queryByName2Lv(String name);
@Query("SELECT * FROM "+ UserModel.USER_TABLE_NAME + " WHERE "+
UserModel.NAME + " = :name")
UserModel queryByName2Model(String name);
@Query("SELECT * FROM "+ UserModel.USER_TABLE_NAME + " WHERE "+
UserModel.FACE_ID + " = :faceId")
LiveData<UserModel> queryByFaceId2Lv(String faceId);
@Query("SELECT * FROM "+ UserModel.USER_TABLE_NAME + " WHERE "+
UserModel.FACE_ID + " = :faceId")
UserModel queryByFaceId2Model(String faceId);
@Query("SELECT COUNT(*) FROM " + UserModel.USER_TABLE_NAME)
int count();
@Query("SELECT * FROM " + UserModel.USER_TABLE_NAME)
LiveData<List<UserModel>> queryAllByLv();
@Query("SELECT * FROM " + UserModel.USER_TABLE_NAME)
List<UserModel> queryAll();
@Update
public int updateUsers(List<UserModel> userModels);
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insertUser(UserModel userModel);
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insertAllUser(List<UserModel> userModels);
@Delete
void delete(UserModel... userModels);
@Delete
void deleteAll(List<UserModel> userModels);
@Query("DELETE FROM " + UserModel.USER_TABLE_NAME + " WHERE " +
UserModel.FACE_ID + " = :faceId")
int deleteByFaceId(String faceId);
}
4.使用DataBase注解创建数据库类
@Database(entities = {UserModel.class},version = 1, exportSchema = true)
public abstract class RoomDemoDatabase extends RoomDatabase {
public abstract UserDao userDao();
public static final String DATABASE_NAME = "room_demo";
private static RoomDemoDatabase sInstance;
public static RoomDemoDatabase getInstance(Context context) {
if (sInstance == null) {
synchronized (RoomDemoDatabase.class) {
if (sInstance == null) {
sInstance = buildDatabase(context);
}
}
}
return sInstance;
}
private static RoomDemoDatabase buildDatabase(final Context appContext) {
return Room.databaseBuilder(appContext, RoomDemoDatabase.class, DATABASE_NAME)
.allowMainThreadQueries()
// .openHelperFactory(new SafeHelperFactory("123456".toCharArray()))
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
}
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
}
})
.build();
}
}