persistence@glassfish.java.net

Re: can you set the persistence-unit data-source at runtime?

From: Nitin Nahata <nitin.nahata_at_gmail.com>
Date: Fri, 20 Oct 2006 19:00:53 -0700

I have a web application that needs to talk to a particular JDBC
data-source registered in the appserver JNDI tree. But my application
does not know the JNDI-name of this data-source until after the app
has been deployed and started.

So I cannot set the correct value for the <jta-data-source> element in
persistence.xml while building the application. I would like to be
able to "inject" it at runtime.

I am not aware of the implementation details but I guess one way to do
this could have been to have below methods in
javax.persistence.EntityManagerFactory:

1. setDataSource( javax.sql.DataSource ds ) or
2. createEntityManager( javax.sql.DataSource ds )
3. or both 1 and 2

Which would let you have code like below:

public class AController {

    @PersistenceUnit(unitName = "myPU")
    private EntityManagerFactory emf;

    //constructor
    AController( javax.sql.DataSource ds ) {
        emf.setDataSource( javax.sql.DataSource ds );
     }

    private EntityManager getEntityManager( ) {
       return emf.createEntityManager();
    }

   public List<A> getAll() {
       EntityManager em = getEntityManager();
       ....
       ....
   }

}

But since I dont see the above methods in the api, I was wondering if
there is some other way to achieve this?

Thanks
Nitin




On 10/20/06, Marina Vatkina <Marina.Vatkina_at_sun.com> wrote:
> Hi Nitin,
>
> Can you be a bit more specific at what are you trying to accomplish?
>
> thanks,
> -marina
>
> Nitin Nahata wrote:
> > data-source for a persistence-unit is set in the persistence.xml file.
> > Which means that it should be known at compile time.
> >
> > Is there a way to set the data-source at runtime instead?
> >
> > Thanks
> > Nitin
>
>