具有默认值的 ORMLite 列
ORMLite column with default
我有一个用默认值定义的非空列:
@DatabaseField(dataType = DataType.TIME_STAMP, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL")
private Date createdDate;
尝试保存未设置 createdDate
字段的行时,出现以下错误:
[SQLITE_CONSTRAINT_NOTNULL] A NOT NULL constraint failed (NOT NULL constraint failed:
ORMLite 可能试图明确地将 NULL
值插入该字段。将 persisted = false
添加到注释中可以避免这种情况,但随后不会在 table 创建时创建该列。
有没有办法在创建列的同时告诉 ORMLite 在 INSERT 时忽略该列?
Is there a way to create the column, but to also tell ORMLite to ignore that column on INSERT?
您缺少的是 readOnly = true
setting for @DatabaseField
。引用 javadocs:
Set this to be true (default false) if this field is a read-only field. This field will be returned by queries however it will be ignored during insert/create statements. [ just added: ] This can be used to represent create or modification dates with the values being generated by the database.
我只是使用了以下字段定义(至少有 H2)并且工作正常:
@DatabaseField(columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL",
readOnly = true, canBeNull = false)
private Date createdDate;
您不需要指定 dataType
,如果您这样做,我认为您的字段应该是 Timestamp
类型。顺便说一句,我刚刚更正的在线文档中缺少此功能。
我有一个用默认值定义的非空列:
@DatabaseField(dataType = DataType.TIME_STAMP, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL")
private Date createdDate;
尝试保存未设置 createdDate
字段的行时,出现以下错误:
[SQLITE_CONSTRAINT_NOTNULL] A NOT NULL constraint failed (NOT NULL constraint failed:
ORMLite 可能试图明确地将 NULL
值插入该字段。将 persisted = false
添加到注释中可以避免这种情况,但随后不会在 table 创建时创建该列。
有没有办法在创建列的同时告诉 ORMLite 在 INSERT 时忽略该列?
Is there a way to create the column, but to also tell ORMLite to ignore that column on INSERT?
您缺少的是 readOnly = true
setting for @DatabaseField
。引用 javadocs:
Set this to be true (default false) if this field is a read-only field. This field will be returned by queries however it will be ignored during insert/create statements. [ just added: ] This can be used to represent create or modification dates with the values being generated by the database.
我只是使用了以下字段定义(至少有 H2)并且工作正常:
@DatabaseField(columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL",
readOnly = true, canBeNull = false)
private Date createdDate;
您不需要指定 dataType
,如果您这样做,我认为您的字段应该是 Timestamp
类型。顺便说一句,我刚刚更正的在线文档中缺少此功能。