0

i'm trying to write an EJB3 Stateless Session Bean which gets the parameter "customerCode" (String). Dependent on this "customerCode" i want to create an EntityManager (Persistence.createEntityManagerFactory...) with a (dynamically?) created PersistenceUnit.

I can not define the PU in the persistence.xml, because it's name (and underlying datasource) must be able to be added/removed at runtime (e.g. deploying a new datasource/persistence unit that belongs to a specific customer code).

I could define the PUs in the persistence.xml, because i know all the customerCodes in advance, but if the datasource XML file is missing, i can not deploy my EAR correctly, because the container (JBOSS) looks for a matching datasource.

what can i do? thanks in advance!

those
  • 1

1 Answers1

2

Yes you can do this.A rough cut is below.

private static Map<String, EntityManagerFactory> emfMap 
                     = new HashMap<String, EntityManagerFactory>();
private static List<String>customerCodes;

You need to populate this list of customerCodes obviously before calling populateEmfMap

public static void populateEmfMap()
     {
       for (String customerCode : customerCodes)
       {
          emfMap.put(customerCode,Persistence.createEntityManagerFactory(customerCode));
       }

    }

You can just get it from the Hasmap by key.

Shahzeb
  • 4,745
  • 4
  • 27
  • 40
  • But the customerCode must be a persistance unit name defined in persistance.xml? So you still nead to have a persistance unit defined prior to call Persistence.createEntityManagerFactory? The question here is probably how to reate a persistance unit in runtime. – simonC Feb 21 '12 at 10:12
  • 1
    Interesting concept if that's what OP was after . That will go down to configuration but I can not get my head around the concept creating a new PU especially with out any new deployment or server restart.With out doing any POC I think groovy is surely one candidate but you will still have to modify the script which will not require any restart but still is a lower level task. – Shahzeb Feb 21 '12 at 22:35
  • I heve read somewhere that tihs is not supported by JPA specification, but have also find datanucleus whish seam to support the persistence unit creation in runtime, so It if datanucleus have it it is possible to do, I still need to find out how :-) – simonC Feb 22 '12 at 14:17