Android房间实体,如何处理静态字段?

Android room entity, how to handle static feilds?

我们是否需要在房间中用 @ignore 注释静态字段?

@Entity(tableName = "table_users")
public class User {
    private static final String MY_CONSTANT = "whatever";

    @PrimaryKey(autoGenerate = true)
    public int id;

    public String name;
    public int age;
}

我阅读了 documentation 但没有找到任何相关信息。

Do we need to annotate static fields with @ignore in room?

不,它们会被自动忽略。

您可以通过创建项目然后检查生成的 java 数据库(数据库 class 名称后缀为 _Impl)来查看这一点。 table 将在 createAllTables 方法中定义。

例如:-

@Entity(tableName = "user")
public class User {

    private static final String MY_CONSTANT = "whatever";

    @PrimaryKey
    Long id;
    String userName;
    String userEmail;
    String userPassword;

    public User(){};

    @Ignore
    public User(String userName, String userEmail, String userPassword) {
        this.userName = userName;
        this.userEmail = userEmail;
        this.userPassword = userPassword;
    }
}

结果:-

_db.execSQL("CREATE TABLE IF NOT EXISTS `user` (`id` INTEGER, `userName` TEXT, `userEmail` TEXT, `userPassword` TEXT, PRIMARY KEY(`id`))");

即没有 MY_CONSTANT 列。