带有默认值的 ORMLite 列 [英] ORMLite column with default

查看:72
本文介绍了带有默认值的 ORMLite 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用默认值定义的非空列:

I have a non null column defined with a default:

@DatabaseField(dataType = DataType.TIME_STAMP, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL")私人日期 createdDate;

尝试保存未设置 createdDate 字段的行时,出现以下错误:

When trying to save a row with the createdDate field unset, I get the following error:

[SQLITE_CONSTRAINT_NOTNULL] NOT NULL 约束失败(NOT NULL 约束失败:

ORMLite 可能试图在字段中显式插入一个 NULL 值.将 persisted = false 添加到注释可以避免这种情况,但是在创建表时不会创建列.

ORMLite is probably trying to explicitly insert a NULL value into the field. Adding persisted = false to the annotation avoids this, but then the column isn't being created on table creation.

有没有办法在创建列的同时告诉 ORMLite 在 INSERT 时忽略该列?

Is there a way to create the column, but to also tell ORMLite to ignore that column on INSERT?

推荐答案

有没有办法在创建列的同时告诉 ORMLite 在 INSERT 时忽略该列?

Is there a way to create the column, but to also tell ORMLite to ignore that column on INSERT?

您缺少的是 @DatabaseField 的 >readOnly = true 设置.引用 javadoc:

What you were missing is the readOnly = true setting for @DatabaseField. To quote the javadocs:

如果此字段是只读字段,则将其设置为 true(默认为 false).该字段将由查询返回,但在插入/创建语句期间将被忽略.[刚刚添加:] 这可用于表示创建或修改日期以及数据库生成的值.

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)并且效果很好:

I just used the following field definition (with H2 at least) and it worked fine:

@DatabaseField(columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL",
    readOnly = true, canBeNull = false)
private Date createdDate;

您不需要指定 dataType,如果您指定,您的字段应该是 Timestamp 类型,我相信.顺便说一句,我刚刚更正的在线文档中缺少此功能.

You don't need to specify the dataType and if you do, your field should be a Timestamp type I believe. Btw, this feature was missing from the online documentation which I just rectified.

这篇关于带有默认值的 ORMLite 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆