Inject JPA Entity Manager with Guice and Play

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!


Get Machiel Mail in your inbox!

Of course I have a newsletter, all the cool kids have them! Sign up if you want to get notified of the occasional blog post I write. They will be mostly about Go, or simply about projects I am working on. And it might just turn out that they are interesting!

And if you're wondering, will he send sp... No, I will never send you any spam!

comments powered by Disqus