Creating JPA entity manager programmatically. Hibernate and CDI

A few days ago I had to write an application with some peculiarities that drove me to do something that I didn’t before, creating JPA entity managers programmatically, pretty interesting actually, I managed to create the persistence units that I need dynamically and according to the environment easily.

To make it simple I’ll not put all of them here, neither the full code, just the necessary snippets to help someone that is trying to do this.


Even if you are going to use this approach, even if you have many different environments, one persistence.xml still necessary.

EntityManagerFactory and EntityManager

Here you can see that it’s a MongoDB em and that used some CDI but don’t mind about that, the relevant parts are the properties and the EntityManager creation.

The Repository

How I used CDI, the EntityManager dependency was easily injected.

The Client

This is how the dependency was injected in here, another simple @Inject annotation.

Configuration and Dependencies

Now, the dependencies, just in case you wanna try 🙂


2 thoughts on “Creating JPA entity manager programmatically. Hibernate and CDI

  1. Great post Alan!
    Just a tip, your text has a typo. When you talk about the client you say “this is how ‘de’ depedency..”. I believe you meant ‘the’.

    Again, great article, keep posting.

Leave a Reply