Change JPA EntityManager connection properties at Runtime

December 30th, 2010 by exhuma.twn

There are many times you want to be able to use different connection options for a JPA EntityManager. The most obvious is different user-credentials (think of a user login-screen and re-using these credentials to connect to the DB), or to make the distinction between development/testing/production environment.

However, if you let Netbeans create the persistence configuration, it will hardcode all connection parameters into the persistence.xml file. When retrieving an EntityManager instance, it will use this information to connect.

If, instead you would like to do this at runtime, you can do the following:

  1. Remove the “properties” tag from the persistence.xml. This may not be necessary, but this will make it clear, that the properties are set inside the code.
  2. Create a “Map<String, String>” which will contain the properties. A list of standard properties can be found in the specs in section
  3. Use this map to create an EntityManagerFactory and use this to create your EntityManager

An example persistence.xml without properties

<?xml version="1.0" encoding="UTF-8"?>                                          
<persistence version="2.0" xmlns="" xmlns:xsi="" xsi:schemaLo
 <persistence-unit name="myTestPU" transaction-type="RESOURCE_LOCAL">    

In case Netbeans created a method “getEntityManager”, you can safely replace this. Here is an example I currently have in use. The “appConf” instance is a singleton I use to store configuration data in the user’s home folder, and yes, the password is stored in plain-text, but for this test-case I did not need to go any further:

    private EntityManager getEntityManager() {                                  
        Map<String, String> dbProps = new HashMap<String, String>();            
                appConf.get("eclipselink.logging.level", "INFO").toString());  
        // On linux, the GSSAPI is not available. Use a default user/password  
        // pair to connect                                                      
        if ("Linux".equals(System.getProperty(""))) {                    
                    appConf.get("", "my-default-host"),                          
                    appConf.get("db.database", "my-default-db")));                
                    appConf.get("db.user", "my-default-username").toString());          
        } else {                                                                
                    appConf.get("", "my-default-host"),                          
                    appConf.get("db.database", "my-default-db")));                
        EntityManagerFactory fact = Persistence.createEntityManagerFactory("myTestPU", dbProps);
        return fact.createEntityManager();                                      

This example uses eclipselink. All available properties can be found it the EclipseLink Wiki

Posted in Coding Voodoo | 14 Comments »

  • khesraw

    This is exactly what i want but it is not so easy to understand please if you could give some explanation it will be my pleasure…

  • Pingback: how to give database user id and password at runtime not through persistence.xml file()

  • exhuma.twn

    Thanks to Oracle, the link to the specs was broken. I fixed it now.

    @khesraw: What exactly is your problem? What parts do you not understand?

  • exhuma

    What exactly is your problem? What parts do you not understand?

  • exhuma

    Thanks to Oracle, the link to the specs was broken. I fixed it now.

  • Antonio D’Mora

     I have the same problem, I got lost in the part of the Entity Manager, where do I have to write that class??

  • Oliver

    Is it possible to get this working with JTA and CMT? Don’t know how to “tell” the server the EntityManager instance.

  • exhuma

    Oh… can’t tell you much about that. I’m sorry. Don’t have much experience with CMT :(

  • Jamil

    Hello Sir, when I do above, I get following error.

    Caused by: Exception [EclipseLink-4003] (Eclipse Persistence Services – 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
    Exception Description: Configuration error. Class [org.h2.Driver ] not found.

    Any help will be greatly appreciated. Thanks

  • exhuma

    This does not seem to be an issue with the configuration, but rather from your environment. The error message suggests that the specific DB driver your are using is not available on your classpath.

    Can you verify if the H2 jar file is included in your Classpath?

  • Jamil

    Hello, thanks for your reply. I had h2 jar in my path. I fixed this issue by using SessionCustomizer but still I would like to know, how to make this solution happen.

  • exhuma

    Hmmm.. Not quite sure. I have not been actively using Java for over 2 years now. I don’t have any access to that project I wrote this for any more :(

    I am wildly guessing that it may have to do with H2.

    The code I mentioned above is following the docs to the letter, so it looks correct to me. Maybe it’s related to an interaction with something else, or related to the point in time where you run the above code. It’s hard to say.

  • Jamil

    Aha, okay nevermind, I will look into this.

  • exhuma

    Sorry for not being more helpful :(


Recent Posts