Adam Bien's Weblog

Configuring The EntityManager At Injection Time

To configure an EntityManager on-the-fly inject the EntityManagerFactory and expose the EntityManager with custom configuration:

public class EntityManagerConfigurator {

    EntityManagerFactory emf;

    Map<String, String> jpaConfiguration;

    public EntityManager configureEm() {
        EntityManager em = emf.createEntityManager(SynchronizationType.SYNCHRONIZED, jpaConfiguration);
        System.out.println("configuredProperties = " + em.getProperties());
        return em;

Now the EntityManager becomes injectable with @Inject:

public class WorkshopScheduler {

    EntityManager em;


The properties can be exposed via injection or read from java.util.Properties:

public class Configurator {

    public Map<String, String> expose() {
        Map<String, String> jpaConfiguration = new HashMap<>();
        jpaConfiguration.put("eclipselink.logging.level", "FINE");
        return jpaConfiguration;

See also with for JCache based configuration.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home:

NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices


A book about rethinking Java EE Patterns


This is just a workaround. You should not forego the persistence.xml.

Posted by javaservant on February 01, 2016 at 10:24 AM CET #

Welcome to the world of produced EntityManager instances that are not strictly bound to the JTA lifecycle;).

Sure you want to produce @Dependent EntityManagers? We prefer @RequestScoped, usually qualified.

Posted by Jens Schumann on February 01, 2016 at 12:43 PM CET #


I never had to configure an EntityManager on-the-fly in projects, but I was asked about that in:



Posted by adam on February 02, 2016 at 09:53 AM CET #

We even use it for tenant support in JPA, e.g. to switch a schema (via Persistence.createEMF())

Nevertheless: Please add a scope;). The example above does not work since it does not honour supported JPA EM scopes. Everything above RequestScoped is non portable.

Posted by Jens Schumann on February 02, 2016 at 11:45 AM CET #

@Jens, Would you mind sharing this piece of code? I´m using Java SE but would like to see how to do it properly in Java EE

Posted by Fábio on February 16, 2016 at 04:54 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments