I'm using spring-jpa
to persist a LocalDateTime created_at
with @CreatedDate
.
@CreatedDate
private LocalDateTime created_at;
Problem: this auto-generates a column with datetime(6)
mysql
column type.
Question: how can I change this to TIMESTAMP
type? I tried @Temporal(TIMESTAMP)
but which is not allowed on LocalDateTime
.
Is it possible at all?
I could get it working with any of the following solutions:
//spring way, with @EnableJpaAuditing on configuration
@EntityListeners(AuditingEntityListener.class)
class MyEntity {
@CreatedDate
@Column(columnDefinition = "TIMESTAMP", nullable = false)
private LocalDateTime created_at;
}
//hibernate way
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date created_at;
//mysql way
@Column(insertable = false, updatable = false,
columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private LocalDateTime created_at;
For the mysql
the important part is: insertable=false
for mysql using the defined DEFAULT CURRENT_TIMESTAMP
, and updatable=false
for ON UPDATE CURRENT_TIMESTAMP
.
Otherwise, the hibernate orm would send created_at=null
as null value to the database, preventing the column definition to take over! Or worse, if you set nullable=false
, the insert would fail although you defined the default timestamp handling for the column.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With