hibernate 4.2.4 添加事件监听

时间:2022-09-11 08:20:09

4.0 以后的版本添加事件的方式:

    

 1 public class HibernateEventWiring {
 2 
 3     private SessionFactory sessionFactory;
 4 
 5     private Map<String, Object> listeners;
 6 
 7 
 8     public void setSessionFactory(SessionFactory sessionFactory) {
 9         this.sessionFactory = sessionFactory;
10     }
11 
12     public void setListeners(Map<String, Object> listeners) {
13         this.listeners = listeners;
14     }
15 
16     @PostConstruct
17     void registerListeners() {
18         Assert.notNull(sessionFactory);
19         EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
20         for (String key : listeners.keySet()) {
21             EventType eventType = EventType.resolveEventTypeByName(key);
22             registry.getEventListenerGroup(eventType).appendListener(listeners.get(key));
23         }
24     }
25 
26 }
public class AccountPostUpdateEventListener implements PostUpdateEventListener {

    @Override
    public void onPostUpdate(PostUpdateEvent event) {
        Object o = event.getEntity();
//do some...
}
1 <bean class="com.xwtec.common.dao.base.HibernateEventWiring">
2         <property name="sessionFactory" ref="sessionFactory" />
3         <property name="listeners">
4             <map>
5                 <entry key="post-update" value-ref="accountUpdateEventListener"></entry>
6             </map>
7         </property>
8     </bean>