@CreatedDate annotation does not work with mysql

Fawzan picture Fawzan · Nov 2, 2016 · Viewed 32.6k times · Source

I am new to spring and I am confused how @CreatedDate annotation works in an entity.

I did a google search and there were many solutions, but none of them worked for me except one. I am confused why?

This is what I tried first

@Entity
@EntityListeners(AuditingEntityListener.class)
public class User implements Serializable {

    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @CreatedDate
    private Date created;

    public User(String name) {

        this.name = name;
    }

    public User() {
    }

It did not work. I got NULL for the value in created column.

Then I did this.

@Entity
@EntityListeners(AuditingEntityListener.class)
public class User implements Serializable {

    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @CreatedDate
    private Date created = new Date();

    public User(String name) {

        this.name = name;
    }

    public User() {
    }

This actually stored the time stamp in the db. My question is most of the tutorials I followed suggested that I do not need new Date() to get the current time stamp. Looks like I do need that. Is there anything I am missing?

Answer

Ismail picture Ismail · Jul 3, 2019

I was Having this issue also and your solution helped me, Thanks, And I add some other annotations to work

Fist make sure you put in SpringApplication Configuration

@SpringBootApplication
@EnableJpaAuditing

Second, make sure you use this annotation on your needed entities

  @Entity
  @Table
  @EntityListeners(AuditingEntityListener.class)