title: Java - Can Hibernate choose between two database configurations in persistence.xml?
body: <p>I have a <strong>Java</strong> app running on <strong>Tomcat 7.0</strong> with <strong>Hibernate</strong> managing the database.</p>
  
  <p>I need to be able to switch the <code>jdbc.url</code> depending on a system environment variable (or possible another flag of sorts). Ultimately, I would like to be able to deploy a <em>staging</em> and <em>production</em> version of my webapp pointing to two different databases. However, at the moment, I have to physically change the <code>jdbc.url</code> value in <code>persistence.xml</code> and re-save it when switching between configurations.</p>
  
  <p>My current <code>persistence.xml</code> file is:</p>
  
  <pre><code>&lt;persistence 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_2_0.xsd"
               version="2.0"&gt;
  
      &lt;persistence-unit name="my_pu" transaction-type="RESOURCE_LOCAL"&gt;
          &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
          &lt;shared-cache-mode&gt;ALL&lt;/shared-cache-mode&gt;
          &lt;properties&gt;
              &lt;property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /&gt;
              &lt;property name="javax.persistence.jdbc.url" value="jdbc:mysql://my.rds.url.goes.here/mydatabase" /&gt;
              &lt;property name="javax.persistence.jdbc.user" value="myusername" /&gt;
              &lt;property name="javax.persistence.jdbc.password" value="mypassword" /&gt;
              &lt;property name="connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/&gt;
          &lt;/properties&gt;
      &lt;/persistence-unit&gt;
  
  &lt;/persistence&gt;
  </code></pre>
  
  <p>I've read about using <code>createEntityManagerFactory()</code> as an option, but I can't find any clean examples of how to implement this. I'm certain this issue has been dealt with before, but I can't find a clean tutorial or advice.</p>
  
  <p>How can I have my Hibernate switch database configurations without having to rewrite the <code>persistence.xml</code> file each time?</p>