带有多个表的预打包房间数据库

prepackaged room db with multiple tables

(基于:

https://gist.github.com/garcia-pedro-hr/9bb5d286d3ea226234a04109d93d020a)

我有一个包含多个 table 的 .db 文件,我想不出如何将它实现到任何应用程序中,我是否应该为每个 table 创建一个实体.db 文件?即使每个 table 都包含精​​确的列?

示例:

table 'b' (
  `Id` int(6) UNSIGNED NOT NULL,
  `Short` text COLLATE utf8_unicode_ci DEFAULT NULL,
  `Full_name` text COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

(上面列出的信息我从“mySQL workbench”)

和来自table 'b'的一段数据:

(6, 'BBI', 'pow. bie.'),
table 'c'(
  `Id` int(6) UNSIGNED NOT NULL,
  `Short` text COLLATE utf8_unicode_ci DEFAULT NULL,
  `Full_name` text COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

和来自table的一段数据 'c':

(3, 'CT', 'Tor.'),

am I supposed to create an entity for every table in the .db file?

  • (基本上必须有一个实体(class用@Entity注解,它也包含在@Database注解定义的实体列表中))

尽管您可以执行以下操作之一来简化问题:-

  1. 合并所有 table 并添加一个列,指示原始 table。您可以使用 prePackagedDatabaseCallback 组合 tables(或相应地预先准备预打包的数据库)。

  2. 使用单个碱基 class 并扩展 class 例如

:-

class BaseTable {

    @PrimaryKey
    Long id;
    @ColumnInfo(name = "short", collate = UNICODE /*? need to check out Room's UNICODE v requirements */ )
    String shrt;
    String full_name;
}

和:-

@Entity(tableName = "b")
class TableB extends BaseTable {
}

和:-

@Entity(tableName = "c")
class TableC extends BaseTable{
}

使用@Database 注释的 class 在实体列表中包括 TableB 和 TableC,例如:-

@Database(entities = {TableB.class,TableC.class},version = 1)

Room 生成一个与 class 同名的 class,用 @Database 注释但后缀为 _Impl,其中有一个名为 createAllTables 的方法,使用上面的方法是:-

@Override
      public void createAllTables(SupportSQLiteDatabase _db) {
        _db.execSQL("CREATE TABLE IF NOT EXISTS `b` (`id` INTEGER, `short` TEXT COLLATE UNICODE, `full_name` TEXT, PRIMARY KEY(`id`))");
        _db.execSQL("CREATE TABLE IF NOT EXISTS `c` (`id` INTEGER, `short` TEXT COLLATE UNICODE, `full_name` TEXT, PRIMARY KEY(`id`))");
        _db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)");
        _db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '1beb9a18d3900d11d1aa0e29c22c5208')");
      }

UNICODE/UTF

Important Note: SQLite only understands upper/lower case for ASCII characters by default. The LIKE operator is case sensitive by default for unicode characters that are beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE. The ICU extension to SQLite includes an enhanced version of the LIKE operator that does case folding across all unicode characters.