Inject JPA Entity Manager with Guice and Play
Answering my own Java questions using a blog post.
December 10, 2014
Recently I’ve been making a lot of use of the Play Framework, overall I am pretty satisfied, but Play makes use of a lot of static helper classes which quickly lead to tightly coupling Play into your code.
For a while I have been trying to find out how to inject the EntityManager
using Guice into my classes without having to call the play.db.JPA
helper
class everywhere.
The reason? Simple, I don’t want to couple my code so tightly to a specific framework. It’s harder to accomplish this with Play (in my opinion), than with for example Spring. But it’s doable.
Before, my code looked like this:
class MyRepository
{
private final EntityManager entityManager;
public MyRepository()
{
entityManager = JPA.em();
}
}
As we should all know by now, this is not neat. Here is how I solved it:
In my Guice module, I added the following method:
@Provides
public EntityManager provideEntityManager()
{
return JPA.em("default");
}
And changed my repository to this:
class MyRepository
{
private final EntityManager entityManager;
@Inject
public MyRepository(final EntityManager entityManager)
{
this.entityManager = entityManager;
}
}
That’s all there is to it. :) Might you have any suggestions or questions, leave a comment!