0

A 'modified at' column can be created in ORMLite by using the version annotation, as described at http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_2.html#index-time-row-last-modified.

Is it possible to define a 'created at' column, which is automatically populated with the current timestamp but unmodified thereafter?

Gray
  • 115,027
  • 24
  • 293
  • 354
Trent Di
  • 65
  • 5

2 Answers2

0

Is it possible to define a 'created at' column, which is automatically populated with the current timestamp but unmodified thereafter?

Yes it can, but this is a per-database operation so the solution depends on which database type you are using. See this answer about Sqlite specifically: How to have an automatic timestamp in SQLite?

The following might work although I'm not sure about the type of the field. It may have to be a Sql java.sql.Timestamp or something:

@DatabaseFile(columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL")
private Date createDate;

For more information see Sqlite's documentation on date-time functions.

Gray
  • 115,027
  • 24
  • 293
  • 354
  • When I define the column using ```@DatabaseField(dataType = DataType.TIME_STAMP, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL")```, I get: ```[SQLITE_CONSTRAINT_NOTNULL] A NOT NULL constraint failed (NOT NULL constraint failed:```. What ORMLite must be doing is 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? – Trent Di Feb 07 '18 at 19:47
  • This should be another question @TrentDi. – Gray Feb 09 '18 at 05:09
  • New [question posted](https://stackoverflow.com/questions/48726207/ormlite-column-with-default) – Trent Di Feb 10 '18 at 22:26
0

This works for SQLite:

@DatabaseField(dataType = DataType.DATE_STRING, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL", readOnly = true, canBeNull = false)
private Date created_at;

As discussed here, readOnly is required so that ORMLite does not try to insert a row with a null timestamp.

Trent Di
  • 65
  • 5