且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring Data @CreatedDate注释对我不起作用

更新时间:2023-08-24 12:11:34

我可能一直处于类似的情况,我希望Spring Data JPA @CreatedDate 注释可以工作,但是不需要进行用户级审计否则在他们的文档中描述。

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.

为了让基于注释的审计工作,我不得不在我的项目中添加一个实现 org的类.springframework.data.domain.AuditorAware 。这很奇怪,因为您实际上似乎并没有使用您将要实现的 getCurrentAuditor()方法返回的值;我只返回 null

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;
    }
}

然后我需要引用我的空对象 AuditorAware 在我的 applicationContext 的条目中实现,以激活JPA审核。我必须确保在指定 jpa:repositories 的行之前执行此操作。这看起来像:

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:

<bean id="auditorBean" class="your.package.subbed.here.NullAuditorBean"/>
<jpa:auditing auditor-aware-ref="auditorBean"/>

我还必须添加 orm.xml file,并且需要正式引用它作为我的 entityManagerFactory bean的属性,如下所示:

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

<property name="mappingResources">
    <value>META-INF/orm.xml</value>
</property>

确保 META-INF / orm.xml 条目与您的编译输出一起存储(我的WAR在我的WAR下 WEB-INF / classes

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

记录中的 orm.xml 文件包含一些样板文件,可以在这个相关的问题

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!