我可以在没有 orm.xml 文件的情况下使用 Spring Data JPA 审计吗(使用 JavaConfig 代替)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22362534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:15:45  来源:igfitidea点击:

Can I use Spring Data JPA Auditing without the orm.xml file (using JavaConfig instead)?

javaspringjpaspring-dataaudit

提问by Eric B.

I'm trying to get Spring Data Auditing to work in my Spring 3.2.8 / Spring Data 1.5 / Hibernate 4 project.

我正在尝试让 Spring Data Auditing 在我的 Spring 3.2.8 / Spring Data 1.5 / Hibernate 4 项目中工作。

As per the Spring Data Auditing docs, I've added the @CreatedBy, etc annotations to my entities, created by AuditorAwareimplementation, and instantiated it from within my JavaConfig. However, it never seems to fire.

根据Spring Data Auditing 文档,我已将@CreatedBy等注释添加到我的实体中,由AuditorAware实现创建,并从我的 JavaConfig 中实例化它。然而,它似乎永远不会着火。

I find the docs a little confusing. It appears that the JavaConfig entry replaces the xml entry, but I am not sure.

我发现文档有点混乱。似乎 JavaConfig 条目替换了 xml 条目,但我不确定。

I don't currently have any orm.xmlfile in my application. To be entirely honest, I'm not even sure where/how to configure it, or why I need it. All my entities are using annotations. I have tried adding @EntityListeners(AuditingEntityListener.class) to the entity, but that has not helped.

orm.xml我的应用程序中目前没有任何文件。老实说,我什至不确定在哪里/如何配置它,或者我为什么需要它。我所有的实体都在使用注释。我曾尝试将 @EntityListeners(AuditingEntityListener.class) 添加到实体中,但这并没有帮助。

My current entity manager is defined without a persistence.xml file:

我当前的实体管理器是在没有 persistence.xml 文件的情况下定义的:

    <!--  entity manager -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
        <property name="packagesToScan" value="com.ia.domain"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.query.substitutions">true '1', false '0'</prop>
                <prop key="hibernate.generate_statistics">true</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
            </props>
        </property>
    </bean>

JavaConfig:

Java配置:

@Configuration
@EnableJpaAuditing
public class AuditConfig {
    @Bean
    public AuditorAware<User> auditorProvider(){
        return new SpringSecurityAuditorAware();
    }
}

Entity:

实体:

@EntityListeners({AuditingEntityListener.class})
@Entity
public class User
{

  @TableGenerator(name="UUIDGenerator", pkColumnValue="user_id", table="uuid_generator", allocationSize=1)
  @Id
  @GeneratedValue(strategy=GenerationType.TABLE, generator="UUIDGenerator")
  @Column(name="id")
  private Long id;

  @NotNull
  private String username;

  @CreatedDate
  @NotNull
  @Temporal(TemporalType.TIMESTAMP)
  @Column(name="created_date", nullable=false)
  private Date createdDate;

  @LastModifiedDate
  @NotNull
  @Temporal(TemporalType.TIMESTAMP)
  @Column(name="last_modified_date", nullable=false)
  private Date lastModifiedDate;

  @CreatedBy
  @ManyToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="created_by")
  private User createdBy;

  @LastModifiedBy
  @ManyToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="last_modified_by")
  private User lastModifiedBy;
  private String password;
  private Boolean enabled;


...
}

I've put a breakpoint in my SpringSecurityAuditorAwareclass but it is never being hit.

我在我的SpringSecurityAuditorAware班级中设置了一个断点,但它从未被击中。

Do I still need an orm.xml file? How/where is this referenced from the EntityManager?

我还需要一个 orm.xml 文件吗?这是如何/从 EntityManager 引用的?

回答by Stephan

Short version: No

简短版本:否

As of JPA 2.0, it is not possible to define such entity listener without an XML file (orm.xml).

从 JPA 2.0 开始,如果没有 XML 文件 ( orm.xml) ,则无法定义此类实体侦听器。

JPA 2.0:

JPA 2.0:

Default entity listeners—entity listeners that apply to all entities in the persistence unit—can be specified by means of the XML descriptor. (p.93)

默认实体侦听器(适用于持久性单元中所有实体的实体侦听器)可以通过 XML 描述符指定。( 第93 页)

Long version: The workaround...

长版:解决方法...

If all entities in your project extends an AbstractAuditablesuperclass then you can put @EntityListeners({AuditingEntityListener.class})on AbstractAuditable. Listeners attached to an entity class are inherited by its subclasses.

如果项目中的所有实体延伸的AbstractAuditable超类,那么你可以把 @EntityListeners({AuditingEntityListener.class})AbstractAuditable。附加到实体类的侦听器由其子类继承。

JPA 2.0:

JPA 2.0:

Multiple entity classes and mapped superclasses in an inheritance hierarchy may define listener classes and/or lifecycle callback methods directly on the class. (p.93)

继承层次结构中的多个实体类和映射超类可以直接在类上定义侦听器类和/或生命周期回调方法。( 第93 页)

Note that a subclass can exclude explicitly an inherited listener using the @ExcludeSuperclassListenersannotation.

请注意,子类可以使用@ExcludeSuperclassListeners注释显式排除继承的侦听器。

There is one last interesting footnote from the spec I'd like to quote:

我想引用规范中最后一个有趣的脚注:

JPA 2.0:

JPA 2.0:

Excluded listeners may be reintroduced on an entity class by listing them explicitly in the EntityListeners annotation or XML entity-listeners element. (Footnote [45] p.97)

通过在 EntityListeners 注释或 XML entity-listeners 元素中明确列出它们,可以在实体类上重新引入被排除的侦听器。(脚注 [45] p.97)



Here is some code for illustrating the workaround:

以下是一些用于说明解决方法的代码:

AbstractAuditableEntity.java

抽象AuditableEntity.java

import java.util.Date;

import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@MappedSuperclass
@EntityListeners({AuditingEntityListener.class}) // AuditingEntityListener will also audit any subclasses of AbstractAuditable...
public abstract class AbstractAuditableEntity {
    @Id
    @GeneratedValue
    private Long id;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdDate;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastModifiedDate;
}

MyEntity.java

我的实体.java

@Entity
public abstract class MyEntity extends AbstractAuditableEntity {

}

I think an interface Auditablemay be used (@EntityListenerscan appear on an interface) instead of an AbstractAuditableclass but I didn't try...

我认为Auditable可以使用接口(@EntityListeners可以出现在接口上)而不是AbstractAuditable类,但我没有尝试...



Reference: JSR-000317 Java Persistence 2.0 - Final Release

参考:JSR-000317 Java Persistence 2.0 - 最终版本

回答by Justin Smith

Using Stephan's answer, https://stackoverflow.com/a/26240077/715640,

使用斯蒂芬的回答,https://stackoverflow.com/a/26240077/715640

I got this working using a custom listener.

我使用自定义侦听器进行了这项工作。

@Configurable
public class TimestampedEntityAuditListener {

    @PrePersist
    public void touchForCreate(AbstractTimestampedEntity target) {
        Date now = new Date();
        target.setCreated(now);
        target.setUpdated(now);
    }

    @PreUpdate
    public void touchForUpdate(AbstractTimestampedEntity target) {
        target.setUpdated(new Date());
    }
}

And then referencing it in my base class:

然后在我的基类中引用它:

@MappedSuperclass
@EntityListeners({TimestampedEntityAuditListener.class})
public abstract class AbstractTimestampedEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;

    @Temporal(TemporalType.TIMESTAMP)
    private Date created;

    @Temporal(TemporalType.TIMESTAMP)
    private Date updated;

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

FWIW, I'm using this in a spring-boot project, without an orm.xml file.

FWIW,我在 spring-boot 项目中使用它,没有 orm.xml 文件。

回答by denov

In 1.9 of spring data you can enable JPA audits with a couple annotations.

在 Spring Data 1.9 中,您可以使用几个注释启用 JPA 审计。

From the docs - http://docs.spring.io/spring-data/jpa/docs/1.9.4.RELEASE/reference/html/#jpa.auditing

从文档 - http://docs.spring.io/spring-data/jpa/docs/1.9.4.RELEASE/reference/html/#jpa.auditing

Using the @EntityListeners(AuditingEntityListener.class)annotation to enable class by class audits. I use it in a base class.

使用@EntityListeners(AuditingEntityListener.class)注释启用逐类审计。我在基类中使用它。

You'll also need @EnableJpaAuditingon a @Configurationclass to enable audits in general.

您还需要@EnableJpaAuditing一个@Configuration类来启用一般的审计。