Room ORM 數(shù)據(jù)庫框架

Room Persistence Library

Android Architecture Components 基本介紹和使用方式見,Android架構(gòu)組件

Room提供了一個抽象層,允許流暢的訪問SQLite數(shù)據(jù)庫,全面強大的直接SQLite。
Android框架提供了支持原始SQL內(nèi)容的內(nèi)置支持。雖然這些API是強大的,但是水平相當?shù)?,需要大量的時間和精力使用:
原始SQL查詢沒有編譯時驗證。由于數(shù)據(jù)圖表的更改,需要手動更新受影響的sql查詢。這個過程是費時和容易出錯的。
你需要使用大量的樣板代碼的SQL查詢和java數(shù)據(jù)對象之間的轉(zhuǎn)換。

Room為了解決這些問題在SQLite提供一個抽象層。
Room有3個主要組成部分:

  • Database: 可以使用此組件創(chuàng)建數(shù)據(jù)庫 holder,注釋定義實體列表,和類的內(nèi)容定義數(shù)據(jù)訪問對象(DAO)數(shù)據(jù)庫中的表。它也是基本連接的主要訪問點。
  • Entity: 實體類對象模型,一般一對一對應(yīng)表結(jié)構(gòu)。實體的每個字段在數(shù)據(jù)庫中都是保存的,除非你用@Ignore 注解。
  • DAO: 數(shù)據(jù)庫操作接口,一般一對一對應(yīng)表的相關(guān)操作
    這些組件,以及它們與應(yīng)用程序其余部分的關(guān)系,如圖所示:
Room結(jié)構(gòu)圖

Entity

User.java

//@Entity用來注解一個實體類,對應(yīng)數(shù)據(jù)庫一張表
@Entity
public class User {
    //@PrimaryKey 主鍵
    @PrimaryKey
    private int uid;
    //@ColumnInfo 對應(yīng)的數(shù)據(jù)庫的字段名成
    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    // Getters and setters are ignored for brevity,
    // but they're required for Room to work.
}

默認情況下,Room為實體中定義的每個成員變量在數(shù)據(jù)中創(chuàng)建對應(yīng)的字段,我們可能不想保存到數(shù)據(jù)庫的字段,這時候就要用道@Ignore注解

@Entity
class User {
    @PrimaryKey
    public int id;

    public String firstName;
    public String lastName;

    @Ignore
    Bitmap picture;
}

注意:為了保存每一個字段,這個字段需要有可以訪問的gettter/setter方法或者是public的屬性

Entity的參數(shù) primaryKeys

每個實體必須至少定義1個字段作為主鍵,即使只有一個成員變量,除了使用@PrimaryKey 將字段標記為主鍵的方式之外,還可以通過在@Entity注解中指定參數(shù)的形式

@Entity(primaryKeys = {"firstName", "lastName"})
class User {
    public String firstName;
    public String lastName;

    @Ignore
    Bitmap picture;
}

Entity的參數(shù) tableName

默認情況下,Room使用類名作為數(shù)據(jù)庫表名。如果你想表都有一個不同的名稱,就可以在@Entity中使用tableName參數(shù)指定

@Entity(tableName = "users")
class User {
    ...
}

和tableName作用類似; @ColumnInfo注解是改變成員變量對應(yīng)的數(shù)據(jù)庫的字段名成

Entity的參數(shù) indices

indices的參數(shù)值是@Index的數(shù)組,在某些情況寫為了加快查詢速度我們可以需要加入索引

@Entity(indices = {@Index("name"), @Index("last_name", "address")})
class User {
    @PrimaryKey
    public int id;

    public String firstName;
    public String address;

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

    @Ignore
    Bitmap picture;
}

有時,數(shù)據(jù)庫中某些字段或字段組必須是唯一的。通過將@Index的unique 設(shè)置為true,可以強制執(zhí)行此唯一性屬性。下面的代碼示例防止表有兩行包含F(xiàn)irstName和LastName列值相同的一組:

@Entity(indices = {@Index(value = {"first_name", "last_name"},
        unique = true)})
class User {
    @PrimaryKey
    public int id;

    @ColumnInfo(name = "first_name")
    public String firstName;

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

    @Ignore
    Bitmap picture;
}

Entity的參數(shù) foreignKeys

因為SQLite是一個關(guān)系型數(shù)據(jù)庫,你可以指定對象之間的關(guān)系。盡管大多數(shù)ORM庫允許實體對象相互引用,但Room明確禁止。實體之間沒有對象引用。

不能使用直接關(guān)系,所以就要用到foreignKeys(外鍵)。

@Entity(foreignKeys = @ForeignKey(entity = User.class,
                                  parentColumns = "id",
                                  childColumns = "user_id"))
class Book {
    @PrimaryKey
    public int bookId;

    public String title;

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

外鍵是非常強大的,因為它允許指定引用實體更新時發(fā)生的操作。例如,級聯(lián)刪除,你可以告訴SQLite刪除所有書籍的用戶如果用戶對應(yīng)的實例是由包括OnDelete =CASCADE在@ForeignKey注釋。ON_CONFLICT : @Insert(onConflict=REPLACE) REMOVE 或者 REPLACE

有時候可能還需要對象嵌套這時候可以用@Embedded注解

class Address {
    public String street;
    public String state;
    public String city;

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

@Entity
class User {
    @PrimaryKey
    public int id;

    public String firstName;

    @Embedded
    public Address address;
}

Dao

UserDao.java

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
           + "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}

數(shù)據(jù)訪問對象Data Access Objects (DAOs)是一種抽象訪問數(shù)據(jù)庫的干凈的方式。

DAO的Insert 操作

當創(chuàng)建DAO方法并用@Insert注釋它時,生成一個實現(xiàn)時會在一個事務(wù)中完成插入所有參數(shù)到數(shù)據(jù)庫。

@Dao
public interface MyDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public void insertUsers(User... users);

    @Insert
    public void insertBothUsers(User user1, User user2);

    @Insert
    public void insertUsersAndFriends(User user, List<User> friends);
}

DAO的Update、Delete操作

與上面的插入類似

@TypeConverte

類型轉(zhuǎn)換,例如:

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();
    }
}

前面的例子定義了2個函數(shù),一個將Date對象轉(zhuǎn)換為一個Long對象,另一個Long到Date的逆轉(zhuǎn)換。因為Room已經(jīng)知道如何保存Long對象,所以可以使用這個轉(zhuǎn)換器來保存類型Date的值。@TypeConverters的使用

@Database(entities = {User.java}, version = 1)
@TypeConverters({Converter.class})
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}
@Entity
public class User {
    ...
    private Date birthday;
}
@Dao
public interface UserDao {
    ...
    @Query("SELECT * FROM user WHERE birthday BETWEEN :from AND :to")
    List<User> findUsersBornBetweenDates(Date from, Date to);
}

Database

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

在創(chuàng)建上述文件之后,您將使用以下代碼獲取創(chuàng)建的數(shù)據(jù)庫實例:

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

Database migration 數(shù)據(jù)庫遷移(升級)

版本迭代中,我們不可避免的會遇到數(shù)據(jù)庫升級問題Room也為我們提供了數(shù)據(jù)庫升級的處理接口;

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");
    }
};

遷移過程結(jié)束后,Room將驗證架構(gòu)以確保遷移正確發(fā)生。如果Room發(fā)現(xiàn)問題,則拋出包含不匹配信息的異常。
警告:如果不提供必要的遷移,Room會重新構(gòu)建數(shù)據(jù)庫,這意味著將丟失數(shù)據(jù)庫中的所有數(shù)據(jù)。

輸出模式

可以在gradle中設(shè)置開啟輸出模式,便于我們調(diào)試,查看數(shù)據(jù)庫表情況,以及做數(shù)據(jù)庫遷移。

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation":
                             "$projectDir/schemas".toString()]
            }
        }
    }
}
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容