Spring Data @CreatedDate annotation doesn't work for me

后端 未结 2 1352
自闭症患者
自闭症患者 2020-12-11 01:33

I am working on project where I use Spring Data. I wanted to fill in creationTime field using @CreatedDate annotation instead using method with

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 02:09

    I may have been in a similar situation where I wanted the Spring Data JPA @CreatedDate annotation to work, but had no need for the user-level auditing that is otherwise described in their documentation.

    To get the annotation-based auditing to work, I had to nonetheless add a class to my project that implemented org.springframework.data.domain.AuditorAware. This is odd because you don't actually seem to use the value returned from the getCurrentAuditor() method that you'll be implementing; mine just returns null.

    public class NullAuditorBean implements AuditorAware {
    
        @Override
        public Object getCurrentAuditor() {
            return null;
        }
    }
    

    I then needed to reference my "null object" AuditorAware implementation in an entry in my applicationContext to activate the JPA auditing. I had to make sure I did this before the line that specifies the jpa:repositories. This looks something like:

    
    
    

    I also had to add an orm.xml file, and needed to formally reference it as a property of my entityManagerFactory bean, like so:

    
        META-INF/orm.xml
    
    

    Make sure this META-INF/orm.xml entry is stored with your compile output (mine is in my WAR under WEB-INF/classes.

    That orm.xml file, for the record, contained some boilerplate, which can be found in the answer to this related question.

    It was a fair amount of work when I got this working. You may prefer your previous working solution!

提交回复
热议问题