When using the Room library, you can define a collection of fields as entities. For each entity, a table is created in the database object associated with it to hold these fields. You must refer to these entities through the Entities list in the Database class. The following code shows how to define an entity

@Entity data class User( @PrimaryKey var id: Int, var firstName: String? , var lastName: String? )Copy the code

To keep a member variable, Room must have access to it, which is either public or provides getter/setter methods (based on JavaBeans conventions)

Entity constructors can be either parameterless (as long as the DAO class has access to the fields to be reserved); You can also include parameters (if you want to save the fields corresponding to those parameters).

Use a primary key

Each entity must define a PrimaryKey, and even if it contains only one member variable, you still need to mark that member variable with @primarykey. If you want the PrimaryKey to increment itself, you can set autoGenerate with the @primarykey property. If your Entity needs to use a compound primary key, you can do so via the primaryKeys attribute of the @Entity annotation, as shown in the following code block:

@Entity(primaryKeys = arrayOf("firstName"."lastName")) data class User( val firstName: String? , val lastName: String? )Copy the code

Room uses the class name as the tableName by default. If you want to customize the tableName, set it via the tableName property of the @entity annotation.

@Entity(tableName = "users")
data class User (
    // ...
)
Copy the code

Note: Table names are case insensitive in SQLite

Like the tableName property, Room uses member variables as database field names. If you want to customize the field name, do so using the @columninfo annotation

@Entity(tableName = "users")
data class User (
    @PrimaryKey val id: Int,
    @ColumnInfo(name = "first_name") val firstName: String? , @ColumnInfo(name ="last_name") val lastName: String?
)
Copy the code

Ignoring member variables

Room creates fields for all member variables of the entity class by default. If you don’t want to keep some member variables, you can use the @ignore annotation

@Entity data class User( @PrimaryKey val id: Int, val firstName: String? , val lastName: String? , @Ignore val picture: Bitmap? )Copy the code

To ignore some variables that inherit from the parent class, you can set the ignoredColumns property of the @entity annotation

open class User {
    var picture: Bitmap? = null
}

@Entity(ignoredColumns = arrayOf("picture"))
data class RemoteUser(
    @PrimaryKey val id: Int,
    val hasVpn: Boolean
) : User()
Copy the code

Table search support is provided

Room provides several types of annotations that make it easier to retrieve data table details. Use full text search on minSdkVersion >= 16 app.

Full text Search

If your app needs fast access to the database via full Text Search (FTS), have your entity use FTS3 or FTS4 to get support for virtual tables. To use this feature, add @fTS3 annotations or @fts4 annotations to the entity using Room 2.1.0 or later.

// Use `@Fts3` only if your app has strict disk space requirements or if you
// require compatibility with an older SQLite version.
@Fts4
@Entity(tableName = "users")
data class User(
    /* Specifying a primary key for an FTS-table-backed entity is optional, but
       if you include one, it must use this type and column name. */
    @PrimaryKey @ColumnInfo(name = "rowid") val id: Int,
    @ColumnInfo(name = "first_name") val firstName: String?
)
Copy the code

Tables with FTS enabled always use a primary key of type Integer with the name “rowid”. If your entity supports FTS, then the primary key should also look like this.

If the table supports content in multiple languages, use the languageId option to specify the store language information for each column.

@Fts4(languageId = "lid")
@Entity(tableName = "users")
data class User(
    // ...
    @ColumnInfo(name = "lid") val languageId: Int
)
Copy the code

Room also provides several other options for ftS-enabled entities, including result sorting, token generator types, and more, FtsOptions

The column index

If your app must support versions that don’t work with FTS3 or FTS4, you can still speed up queries by indexing. Set indexes, including indexes and compound indexes, through the indices attribute of the @Entity annotation.

@Entity(indices = arrayOf(Index(value = ["last_name"."address"]))) data class User( @PrimaryKey val id: Int, val firstName: String? , val address: String? , @ColumnInfo(name ="last_name") val lastName: String? , @Ignore val picture: Bitmap? )Copy the code

Sometimes, a combination of several fields must be unique. You can do this with the unique attribute of the @index annotation.

@Entity(indices = arrayOf(Index(value = ["first_name"."last_name"],
        unique = true)))
data class User(
    @PrimaryKey val id: Int,
    @ColumnInfo(name = "first_name") val firstName: String? , @ColumnInfo(name ="last_name") val lastName: String? , @Ignore var picture: Bitmap? )Copy the code

Includes autovalue-based objects

ps:

AutoValue here refers to a code generation tool.

google/auto

JAVA code generation tools: Lombok, AutoValue and Immutables


Note: This feature is only designed for Java-based entities, in order to achieve the same functionality in Kotlin, it is best to use the Data class

In Room 2.1.0 and later, you can use @AutoValue annotated, Java-based immutable value classes as database entities. This support can be useful if two instances are considered equal because their columns contain the same value.

When using an @autoValue annotated class as an entity, you can use @primaryKey, @Columninfo, @Embedded, and @relation. But when you use these annotations, you’ll have to annotate @copyanannotations so that Room can interpret the auto-generated implementation of this method properly.

@AutoValue
@Entity
public abstract class User {
    // Supported annotations must include `@CopyAnnotations`.
    @CopyAnnotations
    @PrimaryKey
    public abstract long getId();

    public abstract String getFirstName();
    public abstract String getLastName();

    // Room uses this factory method to create User objects.
    public static User create(long id, String firstName, String lastName) {
        returnnew AutoValue_User(id, firstName, lastName); }}Copy the code

0. Overview

1. Use Room entities to define data

2. Define relationships between objects

3. Create a view in the database

4. Use Room DAOs to access data

5. Migrate the database

6. Test the database

7. Reference complex data using Room