Inject a Hibernate Interceptor with Guice / GuicePersist

I'm using JPA with Guice Persist for my GAE projects and Restlet for the REST interface. Under the hood good old Hibernate delivers the JPA service.

在这里输入图像描述在这里输入图像描述

This works like a charm, and Guice injects necessary JPA parts into my classes, for example an EntityManager in the RestletServlet ;

在这里输入图像描述

Now i want to use a SessionInterceptor to insert create/edit timestamps and current active users to my entities. In old projects i used a static HibernateUtil class with ThreadLocal variables to store the sessions. In my new project i want to solve this with Guice. Guice needs to inject an EntityManager in my SessionInterceptor so i can load the current active user from the database.

The SessionInterceptor needs to be created in a Hibernate context and its not permitted to configure this after startup. Therefore i created a SessionInterceptorFactory which uses a Guice Injector. In persistence.xml

在这里输入图像描述

在这里输入图像描述

This works (yes its ugly), i have a SessionInterceptor with Guice Injection.

在这里输入图像描述

But when i try this code;

在这里输入图像描述

[ERROR] 1) No implementation for javax.persistence.EntityManager was bound. [ERROR] while locating com.google.inject.Provider [ERROR]
for the 1st parameter of com.ludus.server.hibernate.SessionInterceptor.(SessionInterceptor.java:20) [ERROR] while locating com.ludus.server.hibernate.SessionInterceptor

I need to connect ( bound ) the JPA (Hibernate) configuration with the SessionInterceptor in Guice like i did with the RestletServlet , but how?

Who can help me with this Guice configuration?

Apart from this, the current SessionInterceptorFactory is a 'dirty Guice hack', is there a clean Guice solution for this?


The problem is that you're creating a brand new (and empty) injector in your SessionInterceptorFactory , when what you want to do is to hook it into the main injector you have elsewhere.

This is a fairly common problem when attempting to integrate Guice into tools that pre-date dependency injection: If the config only gives you the option to provide a "factory class" rather than accepting an instance, then you have no choice but to pass the reference via a static variable. You can make this pretty robust by doing it with a thread-local, but it's not very satisfactory.

In the case of Hibernate however, you can tidy this up by using the API to build your SessionFactory rather than using the configuration file. You can call setInterceptor method on the Configuration object which builds your SessionFactory . You haven't shown how you're creating this at the moment.

链接地址: http://www.djcxy.com/p/94654.html

上一篇: 在Play中重写Guice绑定

下一篇: 用Guice / GuicePersist注入Hibernate拦截器