Android 架构 -- Room

gradle依赖:

// add for room
implementation "android.arch.persistence.room:runtime:1.1.1"
// room 配合 RxJava
implementation "android.arch.persistence.room:rxjava2:1.1.1"
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'

// RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.3'

model对象:

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

@Entity
public class User {
	// 用 @ColumnInfo 来标明数据库表的列名, 用 @PrimaryKey 来标示 主键
	@PrimaryKey(autoGenerate = true)
	private long    uid;
	private String  name;
	private String  address;
	private String  phone;
	private Integer age;

	public long getUid() {
		return uid;
	}

	public void setUid(long uid) {
		this.uid = uid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User{" + "uid=" + uid + ", name='" + name + '\'' + ", address='" + address + '\'' + ", phone='" + phone + '\'' + ", age=" +
			   age + '}';
	}
}

相对应的DAO类:

  1. Room也可以返回RxJava2PublisherFlowable:
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import java.util.List;

import io.reactivex.Flowable;

@Dao
public interface UserDao {

	@Insert(onConflict = OnConflictStrategy.REPLACE)
	List<Long> insert(User... users);

	@Query("SELECT * from user")
	Flowable<List<User>> loadUser();
	
    @Delete
    void delete(User user);
}

当准备好所有的 Model 和 DAO 后,我们就需要把它放入 DataBase 的管理中:

package com.soyoungboy.room.database;

import android.arch.persistence.room.Database;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.TypeConverters;

import com.soyoungboy.room.database.daos.BookDao;
import com.soyoungboy.room.database.daos.UserDao;
import com.soyoungboy.room.database.entities.Book;
import com.soyoungboy.room.database.entities.User;


@Database(entities = {User.class, Book.class}, version = 3)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {

	public abstract UserDao userDao();

	public abstract BookDao bookDao();

}

Converters.java为时间转换的类:

  1. 如果想要在数据库中存储Date,可以存储等价的Unix时间戳
public class Converters {

	@TypeConverter
	public static Date fromTimestamp(Long value) {
		return value == null ? null : new Date(value);
	}

	@TypeConverter
	public static Long dateToTimestamp(Date date) {
		return date == null ? null : date.getTime();
	}
}

Room数据库数据库升级:

  1. Room使用Migration来实现数据库的迁移。每个Migration都指定了startVersionendVersion
import android.app.Application;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.migration.Migration;

public class AppApplication extends Application {

	private AppDatabase mAppDatabase;

	@Override
	public void onCreate() {
		super.onCreate();
		mAppDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "android_room_dev.db")
						   .allowMainThreadQueries()
						   .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
						   .build();
	}

	public AppDatabase getAppDatabase() {
		return mAppDatabase;
	}

	/**
	 * 数据库版本 1->2 user表格新增了age列
	 */
	static final Migration MIGRATION_1_2 = new Migration(1, 2) {
		@Override
		public void migrate(SupportSQLiteDatabase database) {
			database.execSQL("ALTER TABLE User ADD COLUMN age integer");
		}
	};

	/**
	 * 数据库版本 2->3 新增book表格
	 */
	static final Migration MIGRATION_2_3 = new Migration(2, 3) {
		@Override
		public void migrate(SupportSQLiteDatabase database) {
			database.execSQL(
				"CREATE TABLE IF NOT EXISTS `book` (`uid` INTEGER PRIMARY KEY autoincrement, `name` TEXT , `userId` INTEGER, 'time' INTEGER)");
		}
	};
}

操作数据库:

1,首先获取AppDatabase对象:

AppDatabase mAppDatabase = ((AppApplication)getApplication()).getAppDatabase();

2,新增操作:

				User user = new User();
				user.setPhone("18320770932");
				user.setAddress("深圳");
				user.setName("soyoungboy");
				//				user.setAge("28");
				List<Long> ids = mAppDatabase.userDao().insert(user);

3,查询操作:

				mAppDatabase.userDao()
							.loadUser()
							.subscribeOn(Schedulers.io())
							.observeOn(AndroidSchedulers.mainThread())
							.subscribe(new Consumer<List<User>>() {
								@Override
								public void accept(List<User> entities) {
									if (entities != null) {
										for (User user : entities) {
											Log.d("soyoungboy", user.toString());
										}
									}

								}
							});

4,删除操作:

 findViewById(R.id.button_delete_user).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User user = new User();
                user.setPhone("18320770932");
                user.setAddress("深圳");
                user.setName("soyoungboy");
                user.setUid(5);
                UserDao userDao = mAppDatabase.userDao();
                userDao.delete(user);
            }
        });
posted @ 2018-12-12 16:19  西北野狼  阅读(400)  评论(0编辑  收藏  举报