Declaring Hibernate event listeners in a JPA environment

前端 未结 4 1954
陌清茗
陌清茗 2021-02-09 04:24

Hy guys,

I am working on a project developed in Java EE 5 environment. I want to know how I can declare a Hibernate event listener so that I can be informed when CRUD op

4条回答
  •  感情败类
    2021-02-09 04:59

    I assume you are using annotations? If so, you can use the @EntityListeners annotation to do that, like so:

    @MappedSuperclass
    @EntityListeners(AbstractEntityListener.class)
    public abstract class AbstractEntity {
        ...
    }
    

    Your entity listener class could look like this:

    public class AbstractEntityListener {
    
        /**
         * Set creation and lastUpdated date of the entity.
         * 
         * @param entity {@link AbstractEntity}
         */
        @PrePersist
        @PreUpdate
        public void setDate(final AbstractEntity entity) {
            final Date now = new Date();
            entity.setModified(now);
        }
    
    }
    

    There are different annotations available to catch different events, like @PrePersist, @PreUpdate, @PostLoad, etc.

提交回复
热议问题