java - 以编程方式添加 JPA EntityListener/Spring Data AuditingEntityListener

标签 java spring jpa spring-data spring-data-jpa

我正在使用 JPA 和 Spring 的一部分(如事务管理、JPA 存储库),但我不使用 Spring 进行依赖注入(inject),而是将 Spring 部分视为 POJO 对象。到目前为止,它运行良好:我有运行时生成的 JPA 存储库类,事务由 Spring 类管理。

但是,我似乎无法弄清楚如何让 JPA 审计监听器工作。

例如,这是我的 BaseEntity,它定义了 EntityListener 类和审计字段:

@MappedSuperclass
@EntityListeners( { AuditingEntityListener.class } )
public class BaseEntity implements Serializable
{
  @CreatedDate
  @Field( index = Index.YES, store = Store.YES )
  @Column( name = "date_created" )
  @Temporal( TemporalType.TIMESTAMP )
  private Date dateCreated;

  @CreatedBy
  @Column( name = "created_by" )
  private Long createdBy;

  //other stuff
}

您可以看到我指定了 Spring AuditEntityListener 类。应用中的所有其他实体类都扩展了这个 BaseEntity 类。

然后,我有一个实现 AuditorAware 的类:

public class JpaAuditConfiguration implements AuditorAware<Long>
{

  @Override
  public Long getCurrentAuditor()
  {
    //pretend there's real logic here...
    return new Long(0);
  }
}

现在,由于我没有使用 Spring 或 Spring Data 来启动自身,我需要一种方法来使用 AuditingEntityListener 注册此 JpaAuditConfiguration

我的问题:如何以编程方式向 AuditEntityListener 注册 JpaAuditConfiguration

如果有帮助,我正在使用 Spring 类,例如 LocalContainerEntityManagerFactoryBean(以编程方式创建 EntityManagerFactory)和 PersistenceUnitPostProcessor 来完成其余的工作以编程方式配置 JPA。我正在寻找允许我进行上面提到的实体审计监听器注册的 Hook 。

我没有使用任何 orm.xmlpersistence.xml JPA 配置文件。

我该怎么做?

谢谢!!

最佳答案

@Configuration
@EnableJpaAuditing
class Config {

  @Bean
  public AuditorAware<Long> auditorProvider() {
    return new JpaAuditConfiguration ();
  }
}

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.auditing

关于java - 以编程方式添加 JPA EntityListener/Spring Data AuditingEntityListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40597288/

相关文章:

java - 我的 Java 程序出现错误 '.class'

java - 为 MongoDB 生成的 ObjectId

java - 有没有办法在每次使用 Java Controller 方法时调用一个方法?

java - 对于不存在的测试套件,AssertionFailedError Forked Java VM 异常退出

java - 为什么我的自定义 JavaFX MapView 请求通过 OSM 获得 403 错误?

spring - 查询 @DBRef 字段

java - Spring Kafka 与动态 @KafkaListener

hibernate - 从 glassfish 4 迁移到 wildfly 8.1 后,AttributeConverter 失败

hibernate - 二级缓存 - 为什么不缓存所有实体?

java - JPA 属性覆盖