Android技术

android使用Room将数据保存在本地数据库中

2018-07-20  本文已影响244人  风少侠

Room提供了一个覆盖SQLite的抽象层,可以在利用SQLite的全部功能的同时进行更方便、流畅的数据库访问。

添加依赖

为了在自己的应用中使用Room,需要添加architecture组件依赖:

dependencies {
    def room_version = "1.1.1"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version"

    // optional - RxJava support for Room
    implementation "android.arch.persistence.room:rxjava2:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "android.arch.persistence.room:guava:$room_version"

    // Test helpers
    testImplementation "android.arch.persistence.room:testing:$room_version"
}

组成部分

Room有3个主要部分:

示例代码

Entity:

@Entity(primaryKeys = {"account", "pos_curr", "offset", "type"})
public class User {

    @NonNull
    public String account = "";//账号

    public int pos_curr;//当前pos

    @ColumnInfo
    public int pos_end;//总共pos

    @ColumnInfo
    public String qr_str;//二维码长串

    public int offset;//偏移

    @ColumnInfo
    public int multiple;//倍数

    public int type;//1:支付宝  2:微信
    public String deviceId;//设备id


    @Override
    public String toString() {
        return "User{" +
                "account='" + account + '\'' +
                ", pos_curr=" + pos_curr +
                ", pos_end=" + pos_end +
                ", qr_str='" + qr_str + '\'' +
                ", offset=" + offset +
                ", multiple=" + multiple +
                ", type=" + type +
                ", deviceId='" + deviceId + '\'' +
                '}';
    }
}

DAO:

@Dao
public interface UserDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    long insertUser(User user);

    @Delete
    void delAll(User... users);

    @Query("SELECT * FROM User WHERE type = 1  ORDER BY pos_curr DESC,`offset` DESC LIMIT 1")
    User queryLastALi();

    @Query("SELECT * FROM User WHERE type = 2  ORDER BY pos_curr DESC,`offset` DESC LIMIT 1")
    User queryLastWeChat();
}

Database:

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

获取数据库实例:

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "database-name").build();

需要注意的是,在实例化数据库对象时建议使用单例模式,因为每个RoomDatabase的实例代价比较大。

@Database(entities = {User.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase INSTANCE;
    private static final Object sLock = new Object();

    public abstract UserDao userDao();

    public static AppDatabase getInstance(Context context) {
        synchronized (sLock) {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "user.db")
                                .build();
            }
            return INSTANCE;
        }
    }
}

内容详解

Entity

@Entity(primaryKeys = {"account", "pos_curr", "offset", "type"})
public class User {
  ...
}
@Entity(tableName = "table_user", primaryKeys = {"account", "pos_curr", "offset", "type"})
public class User {
    ...
    @ColumnInfo(name = "qr_xxx")
    public String qr_str;//二维码长串
}
@Entity(foreignKeys = @ForeignKey(entity = User.class,
        parentColumns = "id",
        childColumns = "user_id",
        onDelete = ForeignKey.CASCADE,
        onUpdate = ForeignKey.RESTRICT))
public class Book {
    @PrimaryKey
    public int bookId;

    public String title;

    @ColumnInfo(name = "user_id")
    public int userId;
}


@Entity
public class User {
    @PrimaryKey
    public int id;

    public String firstName;
    public String lastName;

    @Ignore
    Bitmap picture;
}
public class Address {
    public String street;
    public String state;
    public String city;

    @ColumnInfo(name = "post_code")
    public int postCode;
}

@Entity
public class User {
    @PrimaryKey
    public int id;

    public String firstName;

    @Embedded
    public Address address;
}

使用DAO访问数据库

注意访问数据库的操作需要在子线程。

增删改

@Dao
public interface UserDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    long insertUser(User user);

    @Delete
    void delAll(User... users);
    
    @Update
    void updateAll(User... users);
}

insert方法为插入一条数据,可以返回rowId。delete和update方法查询数据库中跟传入参数主键相匹配的条目,进行删除或者更新操作,可以返回删除或更新的行数。

@Query("SELECT * FROM User WHERE type = 1  ORDER BY pos_curr DESC,`offset` DESC LIMIT 1")
User queryLastALi();

直接使用sql语句查询,如果返回多个条目,可以用数组接收。

@Query("SELECT * FROM user WHERE age BETWEEN :minAge AND :maxAge")
User[] loadAllUsersBetweenAges(int minAge, int maxAge);
public class NameTuple {
    @ColumnInfo(name="first_name")
    public String firstName;

    @ColumnInfo(name="last_name")
    public String lastName;
}

@Dao
public interface MyDao {
    @Query("SELECT first_name, last_name FROM user")
    public List<NameTuple> loadFullName();
}

Room查询返回first_name和last_name列的值,并且 这些值可以映射到NameTuple类的字段中 。注意也可以使用@Embedded注解。

    @Query("SELECT first_name, last_name FROM user WHERE region IN (:regions)")
    public List<NameTuple> loadUsersFromRegions(List<String> regions);

另外可以配合LiveData和RxJava进行Observable查询和Reactive查询,也可以直接返回一个Cursor,详情参考https://developer.android.google.cn/training/data-storage/room/accessing-data#query-observable

数据库升级

在应用添加或修改功能时,有时候需要增加或修改相应的表,如果单纯升级数据库版本,则会重建数据库,意味着将丢失以前所有的数据。此时可以编写Migration的方式来保存老版本的用户数据,每个Migration指定一个startVersion和endVersion。在运行时,Room会执行每个Migration的migrate方法,使用正确的顺序将数据库迁移到更高版本。

Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
        .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");
    }
};

参考链接:https://developer.android.google.cn/training/data-storage/room/

上一篇下一篇

猜你喜欢

热点阅读