'How to set default current date in jpa for mysql

I am trying to generate current date automatically but getting this error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server 
version for the right syntax to use near 'CURRENT_DATE' at line 1
@Column(name = "ddate", columnDefinition = "DATE DEFAULT CURRENT_DATE")
private Date ddate;


Solution 1:[1]

I would recommend trying the CreationTimestamp annotation paired with nullable = false, updatable = false

@Column(name = "ddate", nullable = false, updatable = false)
@CreationTimestamp
private Date ddate;

The above strategy uses the current VM date, so use this if you are ok with that.

Solution 2:[2]

As a alternative to the @cjnash's answer, there is @CreatedDate annotation which is provided by Spring to keep track of created time of entities.

Main difference of those annotations is @CreationTimestamp applicable to Hibernate only while @CreatedDate applicable to all stores covered by Spring Data: JPA, JDBC, R2DBC, MongoDb, Cassandra and so on.

But for this to work, there are few steps to config.

  1. Annotate Entity class with '@EntityListeners' annotation.

  2. Create fields by annotating them with '@CreatedDate'.

  3. Add @EnableJpaAuditing annotation to 'App' class. This annotation is used to enable auditing in JPA via annotation configuration.

     // Entity Class
     @Entity
     @Table(name = "my_employee")
     @EntityListeners(AuditingEntityListener.class)
     public class Employee {
     .....
     .....
     @CreatedDate
     @Column(name = "ddate")
     private Date ddate;
    
     .....
     .....
    
     }
    
     // App Class
     @SpringBootApplication
     @EnableJpaAuditing
     public class App {
     .....
     .....
     }
    

Check this example for more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cjnash
Solution 2 DevThiman