Room 是goole 在jetpack 中的一个数据库框架,在项目中使用特此记录,以备后查
在项目中使用到了room 数据库框架, 特此记录:
1.添加依赖(用到了annotationProcess, 需要配置在app 使用model 下,不能配置在lib 的model下)
// Room
implementation 'android.arch.persistence.room:runtime:1.1.1'
implementation 'android.arch.persistence.room:rxjava2:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
2.创建一个抽象类,继承自RoomDatabase,提供一个全局的数据库抽象:
@Database(entities = {NewPhotoBean.class,PhotoDescBean.class,PhotoTranslateScaleBean.class},version = 1,exportSchema = false)
public abstract class AppDB extends RoomDatabase{
private static final String DB_NAME="frame.db";
private static volatile AppDB instance;
public static synchronized AppDB getInstance(Context context){
if (instance==null){
instance=create(context);
}
return instance;
}
private static AppDB create(Context context){
return Room.databaseBuilder(
context,
AppDB.class,
DB_NAME)
.allowMainThreadQueries() //配置是否可以在main线程调用数据的操作
//.addMigrations(MIGRATION_1_2)
.build();
}
//数据库升级的配置, 默认的version=1
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
/* database.execSQL("ALTER TABLE department "
+ " ADD COLUMN phone_num TEXT");*/
}
};
//提供给注解实现的抽象方法.
public abstract NewPhotoDao getNewPhotoDao();
}
3…实现@Dao
@Dao
public interface NewPhotoDao {
@Insert
long insert(NewPhotoBean newPhotoBean); //插入单条记录
@Insert
void insert(List<NewPhotoBean> newPhotoBeans); //插入多条记录
@Update
void update(NewPhotoBean newPhotoBean); //根据id 更新记录
@Query("delete from newphoto where path = :path")
int deleteNewPhotoByPath(String path); //使用sql 语句执行删除, 注意 "= :path", 冒号和变量要连着
@Query("delete from newPhoto where path in (:pathList)")
int deleteNewPhotoRecords(List<String> pathList );
@Delete
void delete(NewPhotoBean newPhotoBean);
@Query("delete from newphoto ")
int deleteAllNewPhotoRecords();
@Query("SELECT * FROM newphoto")
List<NewPhotoBean> getAllNewPhoto();
@Query("SELECT * FROM newphoto order by id desc")
List<NewPhotoBean> getAllNewPhotoRxJava();
@Query("SELECT * FROM newphoto order by id desc")
List<NewPhotoBean> getAllNewPhoto();
@Query("SELECT path FROM newphoto order by id desc")
List<String> getAllNewPhotoStr();
@Query("SELECT * FROM newPhoto where path = :path")
NewPhotoBean findNewPhotoRecord(String path);
//@Query("select * from newphoto where userId=(select userId from newphoto order by id desc limit 1) group by path order by id desc")
/* @Query("select * from newphoto where userId=(select userId from newphoto order by id desc limit 1) ")
Single<List<NewPhotoBean>> getLastPersonPhotos();*/
@Insert
long insert(PhotoDescBean photoDescBean );
@Query("SELECT * FROM photoDesc order by id desc")
Single<List<PhotoDescBean>> getAllPhotoDesc();
@Query("SELECT * from photoDesc where photoPath = :filePath")
Single<List<PhotoDescBean>> findPhotoDescByPath(String filePath);
@Query("select * from phototranslatescale where path = :path")
PhotoTranslateScaleBean findPhotoTranslateScale(String path);
@Insert
long insertPhotoTranslateScale(PhotoTranslateScaleBean scaleBean);
@Update
int updatePhotoTranslateScale(PhotoTranslateScaleBean scaleBean);
@Query("delete from phototranslatescale where path = :path")
int deletePhotoTranslateScaleByPath(String path);
@Query("select * from phototranslatescale ")
List<PhotoTranslateScaleBean> getAllPhotoTranslateScale();
}
4.创建bean对象:
@Entity(tableName = "photoDesc")
public class PhotoDescBean {
@PrimaryKey(autoGenerate = true)
private int id; //设置主键
public PhotoDescBean() {
}
private String photoPath;
private String desc;
private long createTime;
private String userId;
private String userName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhotoPath() {
return photoPath;
}
public void setPhotoPath(String photoPath) {
this.photoPath = photoPath;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "PhotoDescBean{" +
"id=" + id +
", photoPath='" + photoPath + '\'' +
", desc='" + desc + '\'' +
", createTime=" + createTime +
", userId='" + userId + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
5, 提供一个数据库管理类:
public class DBUtils {
private static final DBUtils ourInstance = new DBUtils();
private static final String TAG = "DBUtils";
private static AppDB appDB;
public static DBUtils get(Context ctx) {
if (appDB ==null){
appDB=AppDB.getInstance(ctx);
}
return ourInstance;
}
private DBUtils() {
}
public void addPhotoDesc(PhotoDescBean photoDescBean, CallBack callback){
Observable.just("")
.map(s->{
return appDB.getNewPhotoDao().insert(photoDescBean);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(id -> {
if (callback!=null){
callback.onCallback(id);
}
});
}
public void getAllPhotoDesc(CallBack callBack) {
appDB.getNewPhotoDao().getAllPhotoDesc()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
newPhotoBeans -> {
if (callBack!=null){
callBack.onCallback(newPhotoBeans);
}
}
);
}
public void getPhotoDescByPath(String filePath,CallBack callBack){
appDB.getNewPhotoDao().findPhotoDescByPath(filePath)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(photoDescBean -> {
if (callBack!=null){
if (photoDescBean.size()>0){
callBack.onCallback(photoDescBean.get(0));
}else{
callBack.onCallback(null);
}
}
});
}
//==============================NewPhotoBean=============================
public void getAllNewPhotoRecord(CallBack callBack) {
Observable.just("")
.map(s -> {
return appDB.getNewPhotoDao().getAllNewPhoto();
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
newPhotoBeans -> {
if (callBack!=null){
callBack.onCallback(newPhotoBeans);
}
}
);
}
public void getAllNewPhotoRecordStr(CallBack callBack) {
Observable.just("")
.map(s -> {
return appDB.getNewPhotoDao().getAllNewPhotoStr();
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
newPhotoBeans -> {
if (callBack!=null){
callBack.onCallback(newPhotoBeans);
}
}
);
}
public void deleteNewPhotoRecords(List<String> newPhotoBeans, CallBack callBack){
Observable.just("")
.map(s -> {
return appDB.getNewPhotoDao().deleteNewPhotoRecords(newPhotoBeans);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
id -> {
if (callBack!=null){
callBack.onCallback(id);
}
}
);
}
public void deleteAllNewPhotoRecord(CallBack callBack) {
Observable.just("")
.map(s -> {
return appDB.getNewPhotoDao().deleteAllNewPhotoRecords();
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
id -> {
if (callBack!=null){
callBack.onCallback(id);
}
}
);
}
public void deleteNewPhotoByPath(String photo) {
appDB.getNewPhotoDao().deleteNewPhotoByPath(photo);
}
public void deleteNewPhotoByPathAsync(String photo, CallBack callBack) {
Observable.just("")
.map(s -> {
//删除位置记录
//appDB.getNewPhotoDao().deletePhotoTranslateScaleByPath(photo);
return appDB.getNewPhotoDao().deleteNewPhotoByPath(photo);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
id -> {
if (callBack!=null){
callBack.onCallback(id);
}
}
);
}
public void addOrUpdateNewPhotoRecord(NewPhotoBean bean, CallBack callBack) {
Observable.just("")
.map(s -> {
NewPhotoBean newPhotoBean= appDB.getNewPhotoDao().findNewPhotoRecord(bean.getPath());
if (newPhotoBean!=null){
return newPhotoBean.getId();
}else{
return appDB.getNewPhotoDao().insert(bean);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
id -> {
if (callBack!=null){
callBack.onCallback(id);
}
}
);
}
//=========================================PhotoTranslateScaleBean==============================================
public void addOrUpdatePhotoTranslateScale(PhotoTranslateScaleBean scaleBean, CallBack callBack) {
Observable.just("")
.map( s -> {
PhotoTranslateScaleBean bean= getPhotoTranslateScaleByPath(scaleBean.getPath());
if (bean!=null){
//先删除旧记录
appDB.getNewPhotoDao().deletePhotoTranslateScaleByPath(scaleBean.getPath());
}
return appDB.getNewPhotoDao().insertPhotoTranslateScale(scaleBean);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
id->{
if (callBack!=null){
callBack.onCallback(id);
}
}
);
}
public void deletePhotoTranslateScaleByPath(String path) {
appDB.getNewPhotoDao().deletePhotoTranslateScaleByPath(path);
}
public void deletePhotoTranslateScaleByPathAsync(String path, CallBack callBack) {
Observable.just("")
.map(s -> {
return appDB.getNewPhotoDao().deletePhotoTranslateScaleByPath(path);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
id -> {
if (callBack!=null){
callBack.onCallback(id);
}
}
);
}
public PhotoTranslateScaleBean getPhotoTranslateScaleByPath(String path){
return appDB.getNewPhotoDao().findPhotoTranslateScale(path);
}
public void getAllPhotoTranslateScale(CallBack callBack){
Observable.just("")
.map(s -> {
return appDB.getNewPhotoDao().getAllPhotoTranslateScale();
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
newPhotoBeans -> {
if (callBack!=null){
callBack.onCallback(newPhotoBeans);
}
}
);
}
//=========================================数据库操作的回调==================================
public interface CallBack {
void onCallback(Object result);
}
6.在代码中调用:
//删除NewPhoto记录
DBUtils.get(mContext).deleteNewPhotoByPath(realPath);
//删除原图的位置记录
DBUtils.get(mContext).deletePhotoTranslateScaleByPath(realPath);
//删除缩略图的位置记录
DBUtils.get(mContext).deletePhotoTranslateScaleByPath(ScanUtil.generateThumbPathByPhotoPath(realPath));