Declaring Hibernate event listeners in a JPA environment

前端 未结 4 1953
陌清茗
陌清茗 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 05:08

    Note that you can also specify this with annotations on the callback methods. Either embed them in the entity itself, or in a separate class, called an entity listener. Here is a snippet taken from the documentation:

    @Entity 
    @EntityListeners(class=Audit.class)
    public class Cat {
    
        @Id private Integer id;
        private String name;
    
        @PostLoad
        public void calculateAge() {
           ...
        }
    }
    
    public class LastUpdateListener {
    
        @PreUpdate
        @PrePersist
        public void setLastUpdate(Cat o) {
            ...
        }
    }
    

    I guess you can also specify that in the XML config. But annotation are more convenient in my opinion.

提交回复
热议问题