本文介绍了如何在创建时拦截所有 Hibernate 会话(Spring/Grails 环境)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在创建所有新的 Hibernate 会话时拦截它们?我需要访问每个 Session 实例以启用带有参数的 Hibernate 过滤器.

Is there a way of intercepting all new Hibernate sessions when they're created? I need to access each Session instance to enable a Hibernate filter with a parameter.

我使用的唯一解决方案是包装 SessionFactory,但这涉及到很多半讨厌的 hack 以及它需要我实现大约 60 种方法,其中只有少数是有趣的.

The only solution I've gotten working has involved wrapping the SessionFactory, but this involved a lot of semi nasty hacks as well as it required me to implement around 60 methods, where only a few are interesting.

Hibernate 的 SessionFactory 实现由于某些烦人的原因被声明为 final,因此扩展它不是一个选项.我也尝试过方面和 Java 代理,但没有任何运气.

Hibernate's SessionFactory implementation is for some annoying reason declared final so extending it is not an option. I've also tried aspects and Java proxies without any luck.

推荐答案

我已经解决了这个问题(至少在 Hibernate 为此类事情提供合适的 API 之前).解决方案的简短版本:

I've solved this problem (at least until Hibernate provides a proper API for things like this). Short version of the solution:

  1. 代理会话工厂
  2. 拦截对 getCurrentSession 的方法调用,并使用我们已经初始化的 CurrentSessionContext 实现(不是 Hibernate).

更长的版本:http://www.developer-b.com/blog/entry/1635/2010/oct/07/intercepting-hibernate-sessions

来源/Github:http://github.com/multi-tenant/grails-hibernate-hijacker(仍然非常实验性)

Sources / Github:http://github.com/multi-tenant/grails-hibernate-hijacker (still very experimental)

感谢您的输入!

这篇关于如何在创建时拦截所有 Hibernate 会话(Spring/Grails 环境)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 17:19