adam bien's blog

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 {

    @PersistenceUnit
    EntityManagerFactory emf;

    @Inject
    Map<String, String> jpaConfiguration;

    @Produces
    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 {

    @Inject
    EntityManager em;

}

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


public class Configurator {

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

See also github.com/AdamBien/jc2 with github.com/AdamBien/headlands 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: airhacks.io.