gpt4 book ai didi

spring-data-jpa - Spring Data JPA 审计永远不会在运行时被调用

转载 作者:行者123 更新时间:2023-12-05 00:27:22 25 4
gpt4 key购买 nike

我目前正在努力让 Spring Data JPA 审计工作,它目前没有设置字段,并且在使用实体时似乎没有以任何方式被调用。特别是对它如何与持久实体的标准流 Hook 的任何见解都会有所帮助。

我目前正在使用 Spring Data JPA 1.5.0.M1 和 Spring 3.2.6,审计部分的基本配置是:

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
@EnableJpaRepositories(basePackages = "org.myproject.dao")
@EnableTransactionManagement
public class JpaConfig {
...}

在尝试解决此问题时,当前的相关实体用注释和界面进行了标记(注释将是首选)。我意识到不应该这样做,但我暂时复制并粘贴了。
@Entity
public class AutoDraft implements Auditable<Long, Long> {

@SequenceGenerator(name="seq_auto_draft", sequenceName="SEQ_AUTO_DRAFT")
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_auto_draft")
@Id
private Long id;

@CreatedDate
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime createdDate;

@LastModifiedDate
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime lastModifiedDate;

在日志中,正在设置相关的 bean,我可以在启动时捕获在 AuditingEntityListener 中正确配置的 AuditingHandler,但在运行时似乎没有触发任何内容,也没有与特定实体或存储库关联的任何与审计相关的日志消息。我的注意力目前被 AuditingBeanFactoryPostProcessor 吸​​引,但我已经在这方面花费了太长时间,因此可以使用任何帮助。

最佳答案

我知道这是一个老问题,但我遇到了同样的问题,评论帮助我解决了它。所以我想如果有人再次遇到这个问题,我会说得更清楚。

Spring Data 的文档有点误导,因为它暗示您可以简单地通过注释 @Configuration 来启用审计。与 @EnableJpaAuditing 一起上课.

但是,我发现不清楚的部分是您仍然需要修改 orm.xml 文件( https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#auditing ):

<persistence-unit-metadata>   
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="….data.jpa.domain.support.AuditingEntityListener" />
</entity-listeners>
</persistence-unit-defaults>

但是,如果您使用的是纯基于注释的解决方案,则您可能没有 orm.xml 文件。正如 Matt Whipple 在评论中指出的那样,您必须添加 @EntityListeners对实体类进行注释,以便 JPA 持久性库在持久化对象时调用 Spring 审计类(反过来处理审计)。

所以一个完整的例子可能是这样的:
@Configuration
@EnableJpaAuditing
@PropertySource({ "application.properties" })
public class AppConfig {
/**
* Stubbed method for the auditor as the app does not concern itself with auditing any User fields
* Consequently, return null for the current auditor
* @return
*/
@Bean
public AuditorAware<User> auditorProvider(){
return new AuditorAware<User>() {
@Override
public User getCurrentAuditor() {
return <User object that is Logged In>;
}
};
}
}

然后在您的实体上:
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Log {

@Id
@GeneratedValue
private long id;

@CreatedDate
@Column(nullable=false)
private Date createdOn;

// bunch of other audit fields (and other fields)
...
...
}

关于spring-data-jpa - Spring Data JPA 审计永远不会在运行时被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20891129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com