Sadish Kumar
Sadish Kumar

Reputation: 531

does morphia supports automatic timestamp?

Does anyone knows if morphia supports automatic timestamp for create/update of documents in a collection in mongodb during its create/modify operations.

I have already come to know that this support is not available in mongodb. I would like to know if there is any way to get the last access/update time of data or documents in morphia driver.

Thanks, sadish

Upvotes: 1

Views: 1605

Answers (2)

Patrick Twohig
Patrick Twohig

Reputation: 101

Sorry in advance if this isn't the exact answer you're looking for. But the short answer is no.

There appears to be no API in the latest Morphia which supports that operation. Maybe there is a bug opened to support this. In the meantime, you should use your favorite constructor for java.util.Date or java.sql.Timestamp.

The source code for Morphia has the appropriate converter built in to handle this TimestampConverter.java.

Only tangentially related. If your reason for using $currentDate is to avoid clock skew problems among multiple hosts, then you're barking up the wrong tree. Though not explicitly stated in the $currentDate documentation, it is documented that MongoDB does nothing to address clock skew among various hosts. This can be found in the documentation for ObjectId.getTimestamp(). Therefore, the usage of $currentDate is going to provide little benefit as opposed to time-stamping in the client side.

Upvotes: 1

xeraa
xeraa

Reputation: 10859

I'm generally using a base entity, which all other entities extend. It provides the ObjectId, creation date, last change date, a disabled flag,...

The relevant code snippets look like this:

protected Date creationDate;
protected Date lastChange;

// Getters and setters or final setters which don't do anything,
// if you only want to allow the entity to update the values

@PrePersist
public void prePersist() {
    creationDate = (creationDate == null) ? new Date() : creationDate;
    lastChange = (lastChange == null) ? creationDate : new Date();
}

Upvotes: 7

Related Questions