@CreatedDate annotation does not work with mysql

后端 未结 2 379
清酒与你
清酒与你 2021-01-04 02:54

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 fo

相关标签:
2条回答
  • 2021-01-04 03:29

    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)
    
    0 讨论(0)
  • 2021-01-04 03:31

    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"/>
    
    0 讨论(0)
提交回复
热议问题