persistence@glassfish.java.net

Re: Setting persistence.xml properties programmatically

From: Tom Ware <tom.ware_at_oracle.com>
Date: Mon, 28 Jul 2008 09:39:25 -0400

The reason you do not see examples about this in TopLink Essentials-specfic
documentation is that there is a well known JPA-spec-based way to do this.

EntityManagerFactory creation takes a list of properties. Here is how the API
for the Persistence class is defined in the spec:

/**
* Called by Persistence class when an EntityManagerFactory
* is to be created.
*
* @param emName The name of the persistence unit
* @param map A Map of properties for use by the
* persistence provider. These properties may be used to
* override the values of the corresponding elements in
* the persistence.xml file or specify values for
* properties not specified in the persistence.xml
* (and may be null if no properties are specified).
* @return EntityManagerFactory for the persistence unit,
* or null if the provider is not the right provider
*/
public EntityManagerFactory createEntityManagerFactory(String
emName, Map map);

The "map" above is where you would pass your properties. I believe there are
similar ways of doing this when injecting.

FYI: If you are just getting started with a project, I suggesting going to
EclipseLink as your persistence provider since it will be the persistence
provider for newer GlassFish releases and is shipped with GlassFish V3:

http://blogs.sun.com/theaquarium/entry/eclipselink_in_glassfish_v3_as

For information about EclipseLink, the following link is a good starting place:

www.eclipse.org/eclipselink

-Tom


RMMM wrote:
> I'm writing an application that will connect to a database that depends on
> the user. For
> that reason, I can't have the connection information in persistence.xml (the
> schema
> is always the same though). I'm tentatively planning on using TopLink
> Essentials for
> the JPA implementation, assuming I can get answers my questions ...
>
> The connection is determined by 4 properties in the persistence.xml file:
> jdbc driver,
> and the database url, user, and password.
>
> Given the 4 strings (driver, url, user, password), what Java code do I write
> that is
> equivalent to having those in the persistence.xml file?
>
> I'm a little puzzled why this isn't spelled out anywhere I've looked. Isn't
> it one of the
> most obvious, basic issues? I'd think it would be near the beginning of
> almost any
> discussion of JPA or TopLink Essentials ..., but it isn't. Is it documented
> somewhere?
> Is there a snippet of example code I can find? Would someone be kind enough
> to just
> give me the code?
>
> Thanks.