Injecting JPA EntityManager in Google Guice through JBoss Seam
This cool tip describes a 3 step process to use JPA’s EntityManager initialized in JBoss Seam inside the Google Guice environment.
1). Define Seam’s components.xml with entity-manager-factory component as below
<components>
<persistence:entity-manager-factory name="my_persistence_unit"/>
<guice:init injector="#{myInjector}"/>
<guice:injector name="myInjector">
<guice:modules>
<value>mypackage.MyEntityManagerModule</value>
</guice:modules>
</guice:injector>
</components>
where my_persistence_unit is the persistence unit name under META-INF/persistence.xml.
2). Define a Google Guice Module to wire-up Seam’s EnitiyManagerFactory by looking-up based on the expression-value and binding it to Guice context using a Provider
public class MyEntityManagerModule extends AbstractModule
{ public void configure()
{ Expressions expressions = Expressions.instance();
ValueExpression emfVE = expressions.createValueExpression("#{my_persistence_unit}");
EntityManagerFactory emf = (EntityManagerFactory)emfVE.getValue();
EntityManagerProvider.setEntityManagerFactory(emf);
bind(EntityManager.class).toProvider(EntityManagerProvider.class).in(Scopes.SINGLETON);
}
}
class EntityManagerProvider implements Provider
{ static EntityManagerFactory entityManagerFactory = null;
public EntityManager get()
{ return entityManagerFactory.createEntityManager();
}
}
3) One could use the EntityManager anywhere in the Seam-Guice hybrid component:
@Name("hybrid")
@Guice
public class HybridDAO
{ @Inject EntityManager entityManager;
//other DAO methods.
}
This makes Guice components use EntityManager normally use Seam established EntityManagerFactory