Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a @CreatedDate LocalDateTime as Timestamp?

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?

like image 201
membersound Avatar asked Nov 15 '22 16:11

membersound


1 Answers

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.

like image 120
membersound Avatar answered Jan 18 '23 19:01

membersound