title: How to auto-create database, schema and table only if they do not already exist
body: <p>I want to create a simple webapp that </p>
  
  <ul>
  <li>allow remote clients to track some content on a post request</li>
  <li>persist all the tracking in a lightweight database</li>
  <li>give back all the tracking on a get request</li>
  </ul>
  
  <p>About the database, I would like</p>
  
  <ol>
  <li>put its location within a properties file of my webapp (and use this location for hibernate.location.url set in persistence.xml)</li>
  <li>that the database is created with schema and table if they do not exist yet</li>
  <li>use the existing database and schema and table and data if they exist</li>
  </ol>
  
  <p>So I created a maven project with:</p>
  
  <p>pom.xml</p>
  
  <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt;
      &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  
      &lt;groupId&gt;org.my.tracker&lt;/groupId&gt;
      &lt;artifactId&gt;tracker-webapp&lt;/artifactId&gt;
      &lt;version&gt;0.1-SNAPSHOT&lt;/version&gt;
      &lt;packaging&gt;war&lt;/packaging&gt;
      &lt;properties&gt;
          &lt;hibernate.version&gt;4.3.8.Final&lt;/hibernate.version&gt;
          &lt;h2.version&gt;1.4.185&lt;/h2.version&gt;
      &lt;/properties&gt;
  
      &lt;build&gt;
          &lt;plugins&gt;
              &lt;plugin&gt;
                  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                  &lt;artifactId&gt;maven-eclipse-plugin&lt;/artifactId&gt;
                  &lt;version&gt;2.9&lt;/version&gt;
                  &lt;configuration&gt;
                      &lt;downloadSources&gt;true&lt;/downloadSources&gt;
                      &lt;downloadJavadocs&gt;false&lt;/downloadJavadocs&gt;
                  &lt;/configuration&gt;
              &lt;/plugin&gt;
              &lt;!-- Set a compiler level --&gt;
              &lt;plugin&gt;
                  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                  &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
              &lt;/plugin&gt;
              &lt;plugin&gt;
                  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                  &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
                  &lt;version&gt;2.6&lt;/version&gt;
              &lt;/plugin&gt;
          &lt;/plugins&gt;
      &lt;/build&gt;
  
      &lt;dependencies&gt;
          &lt;!-- Servlet API --&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
              &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
              &lt;version&gt;3.1.0&lt;/version&gt;
              &lt;scope&gt;provided&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;!-- JPA Provider (Hibernate) --&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
              &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;
              &lt;version&gt;${hibernate.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
              &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
              &lt;version&gt;${hibernate.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;!-- Database (H2) --&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;com.h2database&lt;/groupId&gt;
              &lt;artifactId&gt;h2&lt;/artifactId&gt;
              &lt;version&gt;${h2.version}&lt;/version&gt;
          &lt;/dependency&gt;
  
      &lt;/dependencies&gt;
  
  &lt;/project&gt;
  </code></pre>
  
  <p>src/main/resources/META-INF/persistence.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
  &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_1_0.xsd" version="1.0"&gt;
  
    &lt;persistence-unit name="thePersistenceUnit" transaction-type="RESOURCE_LOCAL"&gt;
       &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
  
      &lt;class&gt;org.my.tracker.Event&lt;/class&gt;
  
      &lt;properties&gt;
          &lt;property name="connection.driver_class" value="org.h2.Driver"/&gt;
          &lt;property name="hibernate.connection.url" value="jdbc:h2:./db/repository"/&gt;
          &lt;property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/&gt;
          &lt;property name="hibernate.hbm2ddl.auto" value="create"/&gt;
          &lt;property name="hibernate.show_sql" value="true" /&gt;
      &lt;/properties&gt;
  &lt;/persistence-unit&gt;
  &lt;/persistence&gt;
  </code></pre>
  
  <p>src/main/webapp/WEB-INF/web.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
  &lt;web-app 
     xmlns="http://java.sun.com/xml/ns/javaee" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
     version="2.5"&gt;
    &lt;servlet&gt;
      &lt;servlet-name&gt;orc-event&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.my.tracker.EventServlet&lt;/servlet-class&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;orc-event&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/event/*&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <p>src/main/java/org/my/tracker/EventServlet.java</p>
  
  <pre><code>package org.my.tracker;
  
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.util.List;
  
  import javax.persistence.EntityManager;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.Persistence;
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  
  import com.google.gson.Gson;
  
  public class EventServlet extends HttpServlet {
      private static final Logger LOGGER = LoggerFactory.getLogger(EventServlet.class);
  
      private static final long serialVersionUID = 1L;
      public static final String HTML_START="&lt;html&gt;&lt;body&gt;";
      public static final String HTML_END="&lt;/body&gt;&lt;/html&gt;";
      private static EntityManager manager;
  
      static {
          EntityManagerFactory factory = Persistence.createEntityManagerFactory("thePersistenceUnit");
          manager = factory.createEntityManager();
      }
      /**
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          PrintWriter out = response.getWriter();
          try {
              manager.getTransaction().begin();
              @SuppressWarnings("unchecked")
              List&lt;Event&gt; events = manager.createQuery("from Event").getResultList();
              Gson gson = new Gson();
              out.print(gson.toJson(events));
              manager.getTransaction().commit();
          } catch (Exception e) {
              manager.getTransaction().rollback();
          }
      }
  
      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String body = (String)request.getParameter("body");
          if (null != body) {
              try {
                  manager.getTransaction().begin();
                  Event event = new Event();
                  event.setBody(body);
                  manager.persist(event);
                  manager.getTransaction().commit();
              } catch (Exception e) {
                  manager.getTransaction().rollback();
              }
          } else {
              LOGGER.error("null body, cannot track");
          }
      }
  
  }
  </code></pre>
  
  <p>src/main/java/org/my/tracker/Event.java</p>
  
  <pre><code>package org.my.tracker;
  
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.Id;
  
  @Entity
  public class Event {
      @Id
      @GeneratedValue
      private Integer id;
      private String body;
  
      public Integer getId() {
          return id;
      }
  
      public void setId(Integer id) {
          this.id = id;
      }
  
      public String getBody() {
          return body;
      }
  
      public void setBody(String body) {
          this.body = body;
      }
  
  }
  </code></pre>
  
  <p>Well, thanks to all these powerful tools, this is simple and works quite nicely, except that I could not </p>
  
  <ol>
  <li><p>see how to set my db location through a property (is it only possible through tomcat server.xml tune (that I cannot do for it does not belong to me) or spring (which is quite a weak reason to put some spring in my project only for 1 property injection...), </p></li>
  <li><p>(and 3.) each time I launch my webapp, my database is empty. Of course, you will tell me, since I put "create" value in persistence.xml</p>
  
  <pre><code>    &lt;property name="hibernate.hbm2ddl.auto" value="create"/&gt;
  </code></pre></li>
  </ol>
  
  <p>Well, I could put</p>
  
  <ul>
  <li>create-drop : same result as "create" in my case (which is kind of expected, for "drop" does mean a lot like the opposite of "keep everything at shutdown" :D )</li>
  <li>none : but then the database is not created the first time the webapp is not deployed</li>
  <li>validate : well I can recover my content at webapp restart, but as none, at first if it does not exist, the database schema and table are not created and my webapp cannot work with it :)</li>
  </ul>
  
  <p>So I would like if possible to keep things as simple as they are above, is it possible ?</p>
  
  <p>If there is no other way than writing an sql script to initialize my db only if it does not exist, I would appreciate you give the code or some hints, for I am a complete dumb in this field.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>So as I put in one comment, actually, "update" is the value I was looking for.
  Work like a charm.</p>
  
  <p>I did not find any other way than spring to pass variables instead of constant values. But hey that is quite common in such field anyway :) (and spring its orm layer too)</p>