Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Spring manages Hibernate event listeners

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how Spring manages Hibernate event listeners, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!

Hibernate provides event listeners as part of its SPI. You can connect listeners to many events, including pre-insert, post-insert, pre-delete, refresh, and so on.

But sometimes you want to use spring dependencies in these listeners. Hibernate has a good method (the old method doesn't work in the latest version because of the lack of classes).

It's easier this time. All you need is a bean that looks like this:

@ Componentpublic class HibernateListenerConfigurer {@ PersistenceUnit private EntityManagerFactory emf; @ Inject private YourEventListener listener; @ PostConstruct protected void init () {SessionFactoryImpl sessionFactory = emf.unwrap (SessionFactoryImpl.class); EventListenerRegistry registry = sessionFactory.getServiceRegistry () .getService (EventListenerRegistry.class); registry.getEventListenerGroup (EventType.POST_INSERT) .appendListener (listener); registry.getEventListenerGroup (EventType.POST_UPDATE) .appendListener (listener) Registry.getEventListenerGroup (EventType.POST_DELETE) .appendListener (listener);}}

It is similar to this stackoverflow answer, but it doesn't work because it also depends on the deprecated calsses.

You can also inject a List listener (although they do not share a common interface, you can define your own interface).

As pointed out in SO answer, you cannot store new entities in listeners, so it is useless to inject DAO, for example. However, it may be useful to deal with information that does not depend on the current session.

This is all the content of the article "how Spring manages Hibernate event listeners". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report