users@glassfish.java.net

How to inject EntityManager dynamically (runtime)

From: <glassfish_at_javadesktop.org>
Date: Tue, 22 Jan 2008 00:30:40 PST

I have problems to inject EntityManager on runtime.

I have a webservice class with one method which forwards calls to the ejb class.
In my persistence.xml file I described two connections. One of the parameters
of the webservice method accepts persistence unit name to connect to a particular DB.
I need to initialize the EntityManager by passing to the method persistence unit name.

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="ejbPU1" transaction-type="JTA">
    <jta-data-source>DataSource1</jta-data-source>
    <properties/>
  </persistence-unit>
  <persistence-unit name="ejbPU2" transaction-type="JTA">
    <jta-data-source>DataSource2</jta-data-source>
    <properties/>
  </persistence-unit>
</persistence>

SomeWebService.class
@WebService()
@Stateless()
public class SomeWebService
{
  @EJB
  private SomeFacadeLocal ejbRef;

  @WebMethod(operationName = "login")
  public int login(String persistenceUnitName, String arg0, String arg1)
  {
    return ejbRef.login(persistenceUnitName, arg0, arg1);
  }
}

SomeFacadeLocal.class
@Local
public interface SomeFacadeLocal
{
  int login(String persistenceUnitName, String arg0, String arg1);
}

@Stateless
public class SomeFacade implements SomeFacadeLocal
{
  private EntityManager em;
  
  int login(String persistenceUnitName, String arg0, String arg1)
  {
    // dynamic (runtime) injection
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
    ...
  }
}

Classes with persistence.xml are deployed to GlassFish Server V2

I generated webservice client using NetBeans v6 to test my webservice. When I run the client
port.login("ejbPU1","1","2"); I get next exeption:

javax.persistence.PersistenceException: No Persistence provider for EntityManager named ejbPU: The following providers:
oracle.toplink.essentials.PersistenceProvider
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
Returned null to createEntityManagerFactory.

When I use standard EJB injection without dynamic injection it works fine
@PersistenceContext(unitName="ejbPU1")
private EntityManager em;
 

What's wrong in my application?

Thanks!
[Message sent by forum member 'oleg_sokolov' (oleg_sokolov)]

http://forums.java.net/jive/thread.jspa?messageID=255110