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

前端 未结 3 931
感动是毒
感动是毒 2020-12-17 11:18

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

As per the Spring Data Auditing docs, I\'ve added the

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 11:32

    Using Stephan's answer, 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.

提交回复
热议问题