3

I am using Hibernate 5.2.14 through Spring Boot 2.0 with MySQL 5.7.20. I am letting Hibernate generate my Schema (ddl-auto=update, I am aware to only use this during development phase) and I am unable to make Hibernate generate a TIMESTAMP column in the Schema. Things I have tried (in Kotlin):

@Column
var modifiedAt: Instant?

@Column
@Type(type = "timestamp")
var modifiedAt: Instant?

@Column
@Type(type = "Instant")
var modifiedAt: Instant?

@Column
@Temporal(TIMESTAMP)
var modifiedAt: Date?

@Column
@Type(type = "timestamp")
var modifiedAt: Date?

All these generate a DATETIME column in the database. How do I instruct Hibernate to create a TIMESTAMP column? I am aware I could use columnDefinition = "TIMESTAMP", however this is just ramming raw SQL down Hibernate's throat, which seems wrong. Is it really the only way?

0

2 Answers 2

2

As it turns out the Hibernate people are much smarter than me and actually read the MySQL documentation- As it also turns out, TIMESTAMP in MySQL sucks, mostly for being 32-Bit and therefor susceptible to the year-2038-bug. DATETIME is therefor the lesser evil and you just need to make sure to store everything in UTC.

Link to Hibernate Forums: https://discourse.hibernate.org/t/why-does-hibernate-orm-uses-datetime-by-default-on-mysql-instead-of-timestamp/422

Sign up to request clarification or add additional context in comments.

Comments

0

This is how I handle create and update timestamps.

@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
var created: Date = Date()

@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
var modified: Date = Date()

@PreUpdate
protected fun onUpdate() {
    this.modified = Date()
}

3 Comments

You can see in my question that I already tried the java.util.Date + TemporalType.TIMESTAMP combination. Hibernate generates a DATETIME column for this as well.
It does, but it doesn't update the timestamp, that's what the @PreUpdate snippet is for; that will update the timestamp of the modified field every time you persist or merge the entity.
I know how PreUpdate and friends work. That is not my problem. I want a TIMESTAMP column, not DATETIME. DATETIME is something completely different and not at all the correct type to use for TemporalType.TIMESTAMP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.