简体   繁体   中英

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?

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.

You can do one thing Generate the current time according to your required form Using Java there is method called DateTimeFormatter. let me explain through Code:-


LocalDate localDate = LocalDate.now();

DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String Date = dtf.format(localDate);

and then after assign this Date to your field . It will work Fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM