javamysqlspring-bootspring-data-jpaaudit-tables

@CreatedDate annotation does not work with mysql


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?


Solution

  • The @CreatedDate won't work by itself if you just put @EntityListeners(AuditingEntityListener.class) on your entities. In order, it'll work you have to do a little more configuration.

    Let's say that in your DB the field of @CreatedDate is String type, and you want to return the user that is currently logged in as a value for @CreatedDate, then do this:

    public class CustomAuditorAware implements AuditorAware<String> {
    
        @Override
        public String getCurrentAuditor() {
            String loggedName = SecurityContextHolder.getContext().getAuthentication().getName();
            return loggedName;
        }
    
    }
    

    You can write there any functionality that fits your needs, but you certainly must have a bean that reference to a class that implements `AuditorAware

    The second part and equally important, is to create a bean that returns that class with annotation of @EnableJpaAuditing, like this:

    @Configuration
    @EnableJpaAuditing
    public class AuditorConfig {
    
        @Bean
        public CustomAuditorAware auditorProvider(){
            return new CustomAuditorAware();
        }
    }
    

    if your poison is XML configuration then do this:

    <bean id="customAuditorAware" class="org.moshe.arad.general.CustomAuditorAware" />
        <jpa:auditing auditor-aware-ref="customAuditorAware"/>