Using Google Guice to inject JPA EntityManager
June 23rd, 2009
5 comments
I am working on an persistence example using PrimeFaces, Google Guice and Hibernate. Following are the four steps to inject a JPA EntityManager into the Manager (Appfuse parlance) / DAO Layer:
1) Define META-INF/persistence.xml containing JPA Configuration (similar to hibernate.cfg.xml)
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="persdb" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
...
</properties>
</persistence-unit>
</persistence>
2) Create a startup controller Guice bean
@Controller(name="startupBean", startup=true)
public class StartupBean
{ public StartupBean()
{}
}
3) Create a Google Guice Module
public class MyModule implements Module
{ public void configure(Binder binder)
{ AnnotatedBindingBuilder bindingBuilder = binder.bind(MyDataService.class);
ScopedBindingBuilder scopedBuilder = bindingBuilder.to(MyDataServiceImpl.class);
scopedBuilder.in(SINGLETON);
}
}
and create a context parameter in WEB-INF/web.xml
<context-param>
<param-name>optimus.CONFIG_MODULES</param-name>
<param-value>mypackage.MyModule,org.primefaces.optimus.persistence.JPAModule
</param-value>
</context-param>
Note: org.primefaces.optimus.persistence.JPAModule actually injects the EntityManager reading the META-INF/persistence.xml
4) Create the DaraService implementation containing the injected EntityManager
public class MyDataServiceImpl implements MyDataService { @Inject private EntityManager em; //all methods using JPA entityManager here }
No other configuration xmls to be changed. Ain’t it cool!
Categories: Uncategorized