簡體   English   中英

以編程方式添加JPA EntityListener / Spring Data AuditingEntityListener

[英]Add JPA EntityListener/Spring Data AuditingEntityListener Programmatically

我正在使用JPA和Spring的一部分(如事務管理,JPA存儲庫),但我不使用Spring進行依賴注入,而是將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

我的問題:我如何注冊JpaAuditConfigurationAuditEntityListener編程?

如果它有幫助,我使用Spring類,如LocalContainerEntityManagerFactoryBean (以編程方式創建EntityManagerFactory )和PersistenceUnitPostProcessor以編程方式執行其余的JPA配置。 我正在尋找允許我做上面提到的實體審計監聽器注冊的鈎子。

我沒有使用任何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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM