在查看新的Android持久性库的@ColumnInfo文档时,我找不到任何关于如何注释SQL - “DEFAULT”值的信息。
Room是否为默认值提供注释?
我目前的解决方案是手动创建相应的表格......
CREATE TABLE MyTable (
...
MyDefaultValuedCol TEXT DEFAULT 'Default Value',
MyDefaultFlagCol INT DEFAULT 1
)
......并把房间放在最上面。
@Entity(tableName = "MyTable")
class MyClass {
...
public String MyDefaultValuedCol;
public boolean MyDefaultFlagCol;
}
答案 0 :(得分:8)
会议室没有默认值的任何注释,但您可以在实体中设置默认值,如下所示:
@Entity(tableName = "MyTable")
class MyClass {
...
public String MyDefaultValuedCol = "defaultString";
public boolean MyDefaultFlagCol = true;
}
答案 1 :(得分:7)
随着Room Persistence 2.2.0的发布,在@ColumnInfo批注中添加了一个新属性,可用于指定列的默认值。参见documentation。
@Entity(tableName = "users")
data class User(
@PrimaryKey val id: Long,
@ColumnInfo(name = "user_name", defaultValue = "temp") val name: String
@ColumnInfo(name = "last_modified", defaultValue = "CURRENT_TIMESTAMP" ) val lastModified: String
)
答案 2 :(得分:3)
您可以在Entity的getter方法中检查并在其中设置一些默认值。
@Entity(tableName = "Dashboard")
public class Dashboard {
@PrimaryKey
@NonNull
@ColumnInfo(name = "claimNumber")
private String claimNumber;
private String percentage = "0";
private String imagePath = "";
@NonNull
public String getClaimNumber() {
return claimNumber;
}
public void setClaimNumber(@NonNull String claimNumber) {
this.claimNumber = claimNumber;
}
public String getPercentage() {
if (percentage == null || percentage.isEmpty()) {
return "0";
}
return percentage;
}
public void setPercentage(String percentage) {
this.percentage = percentage;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public Dashboard(@NonNull String claimNumber, String percentage, String imagePath) {
this.claimNumber = claimNumber;
this.percentage = percentage;
this.imagePath = imagePath;
}
}
答案 3 :(得分:1)
您可以使用@ColumnInfo
注释设置默认值-
@ColumnInfo(defaultValue = "No name")
public String name;
和
@ColumnInfo(defaultValue = "0")
public int flag;
或用于任何类型的数据类型 从此处查看参考文献Google developer doc
答案 4 :(得分:0)
对于面对这种情况的任何人,当您有两个外键并且“ onDelete = CASCADE”时,可以将外键设置为可以设置为null的数据类型。 例如:
int parent1Id = 0;
int parent2Id = 0;
//should be:
Long parent1Id = null;
Long parent2Id = null;
这样,DB在删除某个特定的对象/行的父对象时会知道该对象/行没有其他不同类型的父对象。