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.


NEW online workshop: WebStandards Igniter (online)

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

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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 #

@Jens,

I never had to configure an EntityManager on-the-fly in projects, but I was asked about that in: https://gist.github.com/AdamBien/c7f79f288782acd237ea

thanks,

adam

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
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License