ORMLite column with default

99封情书 提交于 2019-12-24 20:12:52

问题


I have a non null column defined with a default:

@DatabaseField(dataType = DataType.TIME_STAMP, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL") private Date createdDate;

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

[SQLITE_CONSTRAINT_NOTNULL] A NOT NULL constraint failed (NOT NULL constraint failed:

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.

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


回答1:


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

What you were missing is the readOnly = true setting for @DatabaseField. To quote the 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.

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;

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.



来源:https://stackoverflow.com/questions/48726207/ormlite-column-with-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!